24

I have an SQLite database and am trying to connect to it with PHP. However, I get this error:

Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in C:\xampp\htdocs\deepthi\combadd\combadd_db.php on line 4
Connection to database failed!

What's wrong and how can I fix it?

1
  • Hi @user, welcome to SO. I strongly recommend you use PDO - it's really easy, flexible, and more secure than whatever you (or I) will come up with by yourself (ourselves). net.tutsplus.com/tutorials/php/…
    – Ben
    May 24, 2013 at 5:38

3 Answers 3

36

Try to use PDO instead of sqlite_open:

$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';
$dbh  = new PDO($dir);
$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
8
10

Connecting To Database Following 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();
?>
0
3
<?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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.