How to connect to SQLite database that already exists using PDO?

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 you instantiate this class, it creates a new userquestion.db file, rather than simply opening a connection to the existing file.

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

    
asked by anonymous 16.03.2015 / 02:42

1 answer

2

According to the example available in documentation the file should be accessed by its absolute address, then the name needs to be normalized to have absolute full path .

class Database extends PDO{

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

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

Of course, you can also write the absolute full path manually and not use the realpath() function. Only the filename without the path seems to fail.

I think this is less likely to be the problem, but the documentation recommends using PRAGMA legacy_file_format = TRUE; to match newer versions of SQLite with PDO (which tends to have as many disadvantages as advantages).

    
16.03.2015 / 03:14