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:
<?php
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).
You can try this
$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());
or this
$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");
or this
$query = mysql_query("SELECT * FROM $this_table");
if(!$query)
echo "The ".$this_table." does not exists";
Hope it helps!
$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
$tablesExists[] = $row[0];
}
Use this query and then check the results.
$query = 'show tables like "test1"';
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
Taken from another post
$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;
MySQL way:
SHOW TABLES LIKE 'pattern';
There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php
Checkout that link, there are plenty of useful insight on the comments over there.
Source: Stackoverflow.com