Reputation: 3751
I'm trying to insert into a table, but it cannot find the table users. I get the error posted in the title. The table most definitely exists:
This is how I am connecting:
define("DB_DSN", "sqlite2:host=hosthere;dbname=dbnamehere");
define("DB_USERNAME", " ");
define("DB_PASSWORD", " ");
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
I am using a free website host so I can't really edit much besides .htaccess. It has sqlite and sqlite2. I tried with sqlite:host... but I still get same error. I'm still new to PDO and would appreciate any help.
Upvotes: 0
Views: 31448
Reputation: 108
Your connection string doesn't appear to be correct.
There are no "host" and "dbname" variables for connecting to an SQLite database. An SQLite database is a file, and all you need to open an SQLite database is the file path to this file.
The connection string is made up of the database type (sqlite2 in your case), followed by a colon (:) followed by the full path to your database.
So, for example, if your database is called "mydata.sqlite", and it's in the directory "/home/users/yayu/database", then your connection string would look like this:
sqlite2:/home/users/yayu/database/mydata.sqlite
Thus, to use a constant as you supplied in your example, you would use the following:
define("DB_DSN", "sqlite2:/home/users/yayu/database/mydata.sqlite")
$con = new PDO(DB_DSN)
That is all that's necessary to connect. Each SQLite database file has only one database (unless you explicitely attach another one). So there is no need to specify a database name.
For more information you can refer to the PHP online documentation of the SQLite PDO driver: https://www.php.net/manual/en/ref.pdo-sqlite.php
I think the first thing I would do in your case is to find out where exactly your SQLite database file is located. It looks like you are using a web-based interface to manage your SQLite database. Try to see if there are some settings or similar options that show you the full path to the database. If that doesn't help, contact the hosting provider and ask where the SQLite database file is located.
Upvotes: 3
Reputation: 7228
To ensure a table is in a specific database you can use MySQL SHOW TABLES
to list tables.
Beware of leading spaces in names.
TRY
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->query("SHOW TABLES FROM yayu_zxq_users");
$tables = $stmt->fetchAll(PDO::FETCH_NUM);
print_r($tables);
Upvotes: 1