What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
+2
A:
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Michael Todd
2009-10-06 14:03:49
Oh! Didn't think of that. Let me check if it works as expected!
clops
2009-10-06 14:04:39
maybe I'm missing something, but why would you use this method over SHOW TABLES?
nickf
2009-10-06 14:06:36
@nickf It's part of the ansi standard, so it's portable between different rdbms'es.
troelskn
2009-10-06 14:15:51
@nickf: It also works on databases other than MySQL. This includes PostgreSQL and SQL Server as far as I can tell.
R. Bemrose
2009-10-06 14:16:38
wondering if this is a security exploit you can query information from databases you aren't connected to...
Talvi Watia
2010-09-17 04:41:55
+1
A:
I don't know the PDO syntax for it, but this seems pretty straight-forward:
$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;
nickf
2009-10-06 14:04:13
thanks, totally forgot that SHOW TABLES LIKE could be limited to one exact table only
clops
2009-10-06 14:08:39