SQLite Forum

Select Query will not work in PHP program
Login
I have created a PHP program to generate INSERT queries. However the code to actually insert the record into the database will not work. Attached is the full process. The query produced works just fine if executed in 'sqlitebrowser'.

Hope someone can solve this problem for me as it has happened before and I don't know the cause. Thanks in advance for help.

R

======================================================

//Thu Apr 23, 2020 11:30am

//  ============================  database  ========================

//	From SQLite - PHP INSERT Operation
//  https://www.tutorialspoint.com/sqlite/sqlite_php.htm

	   class MyDB extends SQLite3 {
      function __construct() {
      	global $database;
         $this->open($database); // optumRx.db
      }
   }

   $db = new MyDB();
   if(!$db) {
      echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully<br>";
   }

// ================================================================= 

		$str2.= "'".$recArray['Cost'][$i]."',";           // main part of script dynamicaly building the query
		$str2.= "'".$recArray['ReFills'][$i]."');";
		$query=$str.$str2;
		fwrite($fh, $query."\n\n");                  // write query to log 
		fwrite($fh, "\n  ========================================================\n\n");
		insertRecord($query);                        // call to function to INSERT query to database 
		$str2=" VALUES( ";                           // begin next record
	}	



//  =========================  functions  ==========================

//  Taken From SQLite - PHP INSERT Operation and turned into funtion insertRecord($sql)
//  https://www.tutorialspoint.com/sqlite/sqlite_php.htm


function insertRecord($sql) {
	echo $sql;                 // for testing purposes only
   $ret = $db->exec($sql);
   if(!$ret) {
      echo $db->lastErrorMsg();
   } else {
      echo "Records created successfully\n";  // keep for test only
   }
   $db->close();
}

// Run the program and this is the results:
// Response Payload taken from Firefox Webtools

Opened database successfully // database opened OK

//input query

INSERT INTO rxdata (AcctFor, InvDate, OrderNo, DrugNo, Description, Cost, Refills)         VALUES( 'peter','2020-04-14','123-A','q34','some bizare stuff','4573.87','1');

// If this query is run in "sqlitebrowser" as is shown above it does the insert properly.

ERROR MESSAGE:   This is the problem

[Thu Apr 23 11:12:52.223509 2020] [php7:error] [pid 4918] [client 127.0.0.1:45760] PHP Fatal error:  Uncaught Error: Call to a member function exec() on null in /var/www/db-sql/www/insertQ.php:87\nStack trace:\n#0 /var/www/db-sql/www/insertQ.php(57): insertRecord('INSERT INTO rxd...')\n#1 {main}\n  thrown in /var/www/db-sql/www/insertQ.php on line 87, referer: http://mysql.com/www/insertQuery.html