How to connect to an existing Sqlite database using PDO?

Asked

Viewed 1,552 times

3

I want to connect to a database that already exists using PDO and sqlite in PHP, and here is the code I have:

class Database extends PDO{

     public function __construct(){
        parent::__construct("sqlite: userquestion.db");

        $this->exec("PRAGMA foreign_keys = ON;"); // enable foreign keys
    }
}

However, when I instate this class, it creates a new file userquestion.db, instead of simply opening connection to the existing file.

PS: I have checked and I am using the name and directory correctly.

  • 1

    Is he writing over the existing one? Is there a version compatibility problem? The documentation says something about this. http://php.net/manual/en/ref.pdo-sqlite.php. I doubt this is a problem, but does the whitespace before the name affect anything? In the documentation he picks up the realpath("userquestion.db") before using the file name, is that not it? You say that the directory is correct. Are you sure?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

2

According to the example available at documentation the file must be accessed by its absolute address, so the name needs to be normalized to have the full path.

class Database extends PDO {
     public function __construct() {
        parent::__construct("sqlite:" . realpath("userquestion.db"));
        $this->exec("PRAGMA foreign_keys = ON;"); // enable foreign keys
    }
}

I put in the Github for future reference.

Of course it is also possible to write the absolute full path manually and not use the function realpath(). Only the file name without the path seems to fail.

I find it less likely that this is the problem but the documentation recommends using the PRAGMA legacy_file_format = TRUE; to make newer versions of Sqlite compatible with PDO (which by the way usually has as many disadvantages as advantages).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.