How do I connect to an SQLite database with PHP? [duplicate] How do I connect to an SQLite database with PHP? [duplicate] sqlite sqlite

How do I connect to an SQLite database with PHP? [duplicate]


Try to use PDO instead of sqlite_open:

$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';$dbh  = new PDO($dir) or die("cannot open the database");$query =  "SELECT * FROM combo_calcs WHERE options='easy'";foreach ($dbh->query($query) as $row){    echo $row[0];}$dbh = null; //This is how you close a PDO connection


Connecting To DatabaseFollowing PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.

<?php   class MyDB extends SQLite3   {      function __construct()      {         $this->open('combadd.sqlite');      }   }   $db = new MyDB();   if(!$db){      echo $db->lastErrorMsg();   } else {      echo "Opened database successfully\n";   }?>

Now let's run above program to create our database test.db in the current directory. You can change your path as per your requirement. If database is successfully created then it will give following message:

Open database successfully

SELECT Operation

Following PHP program shows how we can fetch and display records

<?php   class MyDB extends SQLite3   {      function __construct()      {         $this->open('combadd.sqlite');      }   }   $db = new MyDB();   if(!$db){      echo $db->lastErrorMsg();   } else {      echo "Opened database successfully\n";   }   $sql =<<<EOF      SELECT * FROM combo_calcs WHERE options='easy';EOF;   $ret = $db->query($sql);   while($row = $ret->fetchArray(SQLITE3_ASSOC) ){      echo "ID = ". $row['ID'] . "\n";   }   echo "Operation done successfully\n";   $db->close();?>


<?php    if ($db = sqlite_open('sampleDB', 0666, $sqliteerror) ) {         $result = sqlite_query($db, 'select bar from foo');        var_dump(sqlite_fetch_array($result) );     } else {        die($sqliteerror);    }?>

Make sure sqlite support is enable, check phpinfo()

One another solution to your problem is:Using sqlite3 module instead

class DB extends SQLite3{        function __construct( $file )        {            $this->open( $file );        }}$db = new DB( 'sampleDB.sqlite' );