2

In PHP, what would be the best way of seeing if a table exists?

This is what I am using so far

public function TableExists($table) {
    $res = $this->Query("SELECT 1 FROM $table");

    if(isset($res->num_rows)) {
        return $res->num_rows > 0 ? true : false;
    } else return false;
}
Ben
  • 5,627
  • 9
  • 35
  • 49
  • 1
    I would `SHOW TABLES` and search the results for your table name. The above is going to throw an error. – Pekka Mar 10 '13 at 12:43

5 Answers5

15

What you posted is going to throw an error if the table doesn't exist. Try this instead:

SHOW TABLES LIKE 'tablename';

And ensure that you get exactly one row back.

Colin M
  • 13,010
  • 3
  • 38
  • 58
12

Colin has the right solution -- to use SHOW TABLES LIKE. Here is what it would look like using your code:

public function TableExists($table) {
  $res = $this->Query("SHOW TABLES LIKE $table");
  return mysql_num_rows($res) > 0;
}
joshplien
  • 336
  • 1
  • 7
2

For seeing, if [table name] exist

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';
Amir
  • 4,089
  • 4
  • 16
  • 28
1

An alternative to the SHOW TABLES approach from other answers is using the INFORMATION_SCHEMA like this:

SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_SCHEMA = 'your_database_name' AND TABLE_NAME = 'tablename';
johannes
  • 15,807
  • 3
  • 44
  • 57
1
$con = mysqli_connect($hostname,$username,$password,$database);

if(mysqli_num_rows(mysqli_query($con,"SHOW TABLES LIKE 'accman'"))) {
  echo "DB EXIST";
} else {
  echo "DB Not Exist";
}
Attaullah Khan
  • 303
  • 2
  • 8