0

I am working with a php program and want to check if a table exists. If it does exist, do nothing, if it doesn't create and populate the table. I ran across

if(mysql_query("DESCRIBE `table`")) {
    // Exists
}

but this only takes action if it does exist. Would this

if(!mysql_query("DESCRIBE `table`")) {
    // create and populate table
}

do what I am asking?

Doghouse308
  • 489
  • 1
  • 5
  • 7

1 Answers1

1

What you're doing won't work because the test is only testing the return value of the mysql_query() call, not the result of the query itself.

You need to query the tables with SHOW TABLES LIKE 'table' and check the number of rows returned:

$db = new mysqli(...);
$result = $db->query("SHOW TABLES LIKE 'table'");
if ($result->num_rows == 0) {
   // create table
}

Note: mysql_*() is deprecated - you shouldn't use it for new code.

You'll find the MySQL reference here, and the PHP reference for mysqli here

  • Take a look of this [mysql-check-if-table](http://stackoverflow.com/questions/8829102/mysql-check-if-table-exists-without-using-select-from) – carito Nov 04 '14 at 05:39
  • I noticed the different color on the word 'new'. Do I need to include 'new' in that code? – Doghouse308 Nov 04 '14 at 17:47
  • I've used the OOP form of `mysqli`so you'll need `new` if you follow my code. You can use a procedural form - see the PHP manual for details. –  Nov 04 '14 at 17:54