views:

386

answers:

2

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
Oh! Didn't think of that. Let me check if it works as expected!
clops
maybe I'm missing something, but why would you use this method over SHOW TABLES?
nickf
@nickf It's part of the ansi standard, so it's portable between different rdbms'es.
troelskn
@nickf: It also works on databases other than MySQL. This includes PostgreSQL and SQL Server as far as I can tell.
R. Bemrose
wondering if this is a security exploit you can query information from databases you aren't connected to...
Talvi Watia
+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
thanks, totally forgot that SHOW TABLES LIKE could be limited to one exact table only
clops