<?php
// Populate a DB table previously created.
// Thanks to:
// https://www.tutorialspoint.com/sqlite/sqlite_php.htm
// for a starting point

// Class to open or create a DB file.  The constructor takes a db name argument
// This new class extends(uses) the standard SQLite3 libraries.
  
class MyDB extends SQLite3 {
     function 
__construct($dbName) {
        
$this->open($dbName);
     }
  }

// Check if a filename argument was passed to us.  If so do the work.
// Otherwise politely complain.
  
if (isset($argv[1]) and isset($argv[2])) {

// Get the DB filename and the text filename
    
$DBname $argv[1];
    
$textName $argv[2];

// Create a new instance of the MyDB class.  Which will open/create the new DB file
    
$db = new MyDB($DBname);

// Check if it works by seeing if we got a database object.  No complain.
    
if(!$db) {
// It did not open.  Display the error.
      
echo "Could not open: " $db->lastErrorMsg() . "\n";
// It worked.  Tell the user.
    
} else {
      echo 
"Opened/created the  database successfully.\n";
    }
// Open the .csv file    
    
$inFile fopen ($textName'r');
// Continue if it opened OK.
    
if ($inFile) {
// Read lines of the file until end of file.
      
while (! feof($inFile)) {
        
$line fgets($inFile);
// If the line has data continue.  The !feof only works after reading past the end.
        
if ($line){
// Break the line up into its component parts.  Create the SQL and insert the line into the DB
          
list($id$name$image$description) = explode('|'$line);
          
$sql "insert into Minerals (ID, Name, Image, Description)
                  Values (
$id, '$name', '$image', '$description')";
          
$stat $db->exec($sql);
// If this worked continue.
          
if(!$stat) {
            echo 
$db->lastErrorMsg();
          } else {
            echo 
"Record $id added\n";
          }
        }  
      }
    }

// A DB or text filename was not supplied.  Complain.
  
} else {
    echo 
"Please enter a DB name and text file name to use.\n";
}
?>