Test for Database Table in PHP

Sometimes it's handy to be able to detect whether a given table exists, such as when you want to create a table if it isn't present.

The following example will detect the presence of a table in the simplest way I can think of.

 if(mysql_num_rows( mysql_query("SHOW TABLES LIKE 'tablename'"))) {
    // table is present
    // execute some code here

Alternatively, a small change to reverse the logic will let you react if the table does not exist. Note the exclamation point which means "not" and changes the logic to respond if the table does not exist.

 if(!mysql_num_rows( mysql_query("SHOW TABLES LIKE 'tablename'"))) {
    // table is not present
    // here you might want to create the missing table

If you're not familiar with PHP, the logic of the first if() statement says essentially this:

Query the database to see how many tables are named 'tablename'.

Because only one table in the database can have the name, only two responses are possible: 1 or 0. In boolean logic, those values represent Yes/No or True/False respectively and can be acted on.

If the condition is satisfied (yes, the table exists in the first example above or no, the table does not exist in the second example above), the code between the braces {} will be executed.