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:
  1. /* example with table name: table_name */
  2. SHOW TABLES LIKE 'table_name';

This solution will return 1 row if it exists, and 0 rows if it doesn't. Here is a PHP example using this:

PHP:
  1. function DoesTableExist($name)
  2. {
  3.    $sql = "SHOW TABLES LIKE '$name'";
  4.    $result = mysql_query($sql);
  5.    if(mysql_num_rows($result)> 0)
  6.    {
  7.       return true;
  8.    }
  9.    else
  10.    {
  11.       return false;
  12.    }
  13. }
  14.  
  15. if(DoesTableExist('users'))
  16. {
  17.    echo "Users table found!";
  18. }
  19. else
  20. {
  21.    echo "Users NOT FOUND!!!";
  22. }

Related Posts

  1. Presentation: Real Life Scaling Here are my slides for the presentation that I gave at the Utah Open Source Conference on Friday. It was an awesome conference, and I am glad that I was able to be involved. Real Life Scaling: A Tale of Two Websites View more presentations from Justin Carmony. If you...
  2. “Nerfing” a PHP Object I was trying to think of something with PHP I could blog about that would be short and sweet. Then I thought of something that a good friend of my taught me: nerfing objects. The Problem Many times while working with PHP and bigger frameworks, you'll have classes that extend...
  3. jQuery Tip: Better Toggle For many web developers, jQuery is the most awesome JavaScript library out there. For me, it has turned JavaScript from being a nightmare into a power tool. I love JavaScript now, where as before I truely hated it. Takes all the hassel out of most compatibility issues across browsers. I...

Posted in Programming. Tagged with , , , .

2 Responses

Comments RSS Feed.

  1. Patrizio said

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

Continuing the Discussion

  1. autocarsinsurance.net » Blog Archive » MySQL - Does Table Exist w/o Throwing Errors linked to this post on November 3, 2008

    [...] 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:. PLAIN TEXT. Read more [...]

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.

Powered by WP Hashcash