Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi Table Exists

Tags:

php

mysqli

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;
}
like image 520
Ben Avatar asked Mar 21 '26 18:03

Ben


1 Answers

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.

like image 128
Colin M Avatar answered Mar 24 '26 08:03

Colin M