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, SQLite, etc.
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, SQLite, etc.
At first, I was using the accepted answer, but then I noticed it was failing with empty tables. Here is the code I'm using right now:
function DB_table_exists($db, $table){
GLOBAL $db;
try{
$db->query("SELECT 1 FROM $db.$table");
} catch (PDOException $e){
return false;
}
return true;
}
This code is an extract of my extension class for PDO. It will produce an error (and return false) if the table doesn't exist, but will succeed if the table exists and/or is empty.
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 recommend you to use DESCRIBE
example query:
DESCRIBE `users`
example php&pdo:
$tblname = 'users'; //table name
$x = $db->prepare("DESCRIBE `$tblname`");
$x->execute();
$row = $x->fetch();
if ($row) {
print 1; //table exists
}else{
print 0; //table not exists
}
A simple PDO two liner that works with MySQL (not sure about other DBs):
$q = $pdo->query("SHOW TABLES LIKE '{$table}'");
$tableExists = $q->fetchColumn();
Do a query where you ask the database to create a table if it doesn't exist:
$string = "CREATE TABLE IF NOT EXISTS " .$table_name . " int(11) NOT NULL AUTO_INCREMENT,
`id` int(3) NOT NULL,
`blabla` int(2) NOT NULL,
`blabla1` int(2) NOT NULL,
`blabla3` varchar(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=1 ";
$sql = $conection->prepare($string);
$sql->execute();
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;";