Mohammad Saberi Mohammad Saberi - 5 months ago 36
MySQL Question

check if MySQL table exists or not

Possible Duplicate:

MySQL check if a table exists without throwing an exception

I have a dynamic mysql query builder in my project that creates select queries from different tables.

I need to check if the current processing table exists or not.

Imagine that my tables are table1, table2, and table3. My code is something like this:

for($i = 1 ; $i <= 3 ; $i++) {
$this_table = 'table'.$i;
$query = mysql_query("SELECT * FROM $this_table");
// ...

How can I do this check (Please tell me the simplest way).


Update mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
else {
    echo "Table does not exist";

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.