2

在 PHP 中,查看表是否存在的最佳方法是什么?

这是我到目前为止使用的

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;
}
4

5 回答 5

15

如果表不存在,您发布的内容将引发错误。试试这个:

SHOW TABLES LIKE 'tablename';

并确保您准确地返回一排。

于 2013-03-10T12:44:20.303 回答
12

Colin 有正确的解决方案——使用SHOW TABLES LIKE. 这是使用您的代码的样子:

public function TableExists($table) {
  $res = $this->Query("SHOW TABLES LIKE $table");
  return mysql_num_rows($res) > 0;
}
于 2013-03-10T12:51:19.220 回答
2

用于查看,如果[table name]存在

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';
于 2013-03-10T13:09:23.163 回答
1

其他答案的方法的替代SHOW TABLES方法是使用INFORMATION_SCHEMA这样的:

SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_SCHEMA = 'your_database_name' AND TABLE_NAME = 'tablename';
于 2013-03-10T13:11:37.273 回答
0
$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";
}
于 2019-04-27T09:17:45.690 回答