I want to check if a table with a specific name exists in a database I\'ve connected to using PHP and PDO.
It has to work on all database backends, like MySQL, SQLi
This seems to work at least with SQLite3 without exceptions, etc:
$select =
"SELECT CASE WHEN EXISTS (SELECT * FROM SQLITE_MASTER WHERE TYPE = 'table' AND NAME = :tableName) THEN 1 ELSE 0 END AS TABLE_EXISTS;";
Before I go on, I do realise this is a MySQL-specific solution.
While all the solutions mentioned here may work, I (personally) like to keep PDO from throwing exceptions (personal preference, that's all).
As such, I use the following to test for table creation instead:
SHOW TABLES LIKE 'some_table_of_mine';
There's no error state generated if the table doesn't exist, you simply get a zero resultset. Works fast and consistently for me.
If you have other major actions to do within the same statement, you can use the e->errorInfo
try{
//Your major statements here
}
catch(PDOException $e){
if($e->errorInfo[1] == 1146){
//when table doesn't exist
}
}
I do a few things in my web apps with CodeIgniter to check that the database exists (and is useful), any of these can work:
@$this->load->database();
$v = @$this->db->version()
$tables = @$this->db->list_tables();
Adding the @
will suppress errors if you have them enabled in your PHP setup, and checking the results of version()
and list_tables()
can be used to not only determine if your DB is around (but that it's sane too).
You might be able to avoid having to rely on an error by using a query along the lines of "SHOW TABLES LIKE 'your_table'" and then counting the rows. I've been using this method successfully with MySQL and PDO but have yet to test it with other DBs
Do:
select 1 from your_table
and then catch the error. If you don't get any error, but resultset with one column containing "1", then the table exists.