There are times where you would like to know if a table exists before executing an query. Most solutions require having MySQL throw an error saying “table does not exist,” but I prefer a cleaner way. I found on this forum post a clean way to do it:
[sql]
/* example with table name: table_name */
SHOW TABLES LIKE ‘table_name’;
[/sql]
This solution will return 1 row if it exists, and 0 rows if it doesn’t. Here is a PHP example using this:
[php]
function DoesTableExist($name)
{
$sql = “SHOW TABLES LIKE ‘$name'”;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
return true;
}
else
{
return false;
}
}
if(DoesTableExist(‘users’))
{
echo “Users table found!”;
}
else
{
echo “Users NOT FOUND!!!”;
}
[/php]
Great job, it definitely solved me a problem. Thanks.
LikeLike