如何检查MySQLi中是否存在表?

时间:2014-03-16 14:35:35

标签: php mysql mysqli

这就是我正在做的事情:

$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$db_name." AND table_name = users");
$nr = $result->num_rows; // 77 line
var_dump($nr);
$mysqli->close();

但错误说:

Notice: Trying to get property of non-object in test.php on line 77
NULL

3 个答案:

答案 0 :(得分:2)

您也可以使用此声明SHOW TABLES LIKE 'tablename';

进行检查

答案 1 :(得分:1)

要使你的方法有效,你需要围绕字符串常量引用:

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '".$db_name."' AND table_name = 'users';

但是,要使您的方法真正发挥作用,请执行以下操作:

SELECT 1
FROM information_schema.tables
WHERE table_schema = '".$db_name."' AND table_name = 'users';

您正在查看返回的行数,而不是count(*)的值。

答案 2 :(得分:-1)

SELECT COUNT(*) FROM `table_name` WHERE FALSE;

<强>: - )

成功意味着表存在,失败......意味着它没有!