Basic Queries using SQLite3 class

Posted under » PHP on 2 Feb 2023

Please read the earlier article for using SQLite with PDO.

An simple example of extending the SQLite3 class and changing the __construct parameters, then using the open method to initialize the DB.

<¿php 
   class MyDB extends SQLite3
   {
   function __construct()
    {
      $this->open('mysqlitedb.db');
       }
         }
         $db = new MyDB();
         $db->exec('CREATE TABLE foo (bar STRING)');
         $db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

          $result = $db->query('SELECT bar FROM foo');
          var_dump($result->fetchArray());
?>

An example of the object oriented way.

<¿php 
 class MyDB extends SQLite3 {
           function __construct() {
              $this->open('chinook.db');
           }
        }
        $db = new MyDB();
        if(!$db) {
           echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully\n";
   }
   $sql = 'SELECT * from customers';
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
   echo "<p>ID = ". $row['CustomerId'] . "\n";
   echo "
Name = ". $row['FirstName'] ."\n"; echo "
Lastname = ". $row['LastName'] ."\n"; echo "
Company = ".$row['Company'] ."\n\n"; } echo "<p>
Operation done successfully\n"; $db->close(); ?>

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data