MySQL – Does Table Exist w/o Throwing Errors

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]

2 thoughts on “MySQL – Does Table Exist w/o Throwing Errors

  1. Great job, it definitely solved me a problem. Thanks.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close