Php MySQLi如何检查表是否存在?
如果没有这样的表,我想按应用程序创建表。但是第一次这么做。。。需要帮忙吗,thoPhp MySQLi如何检查表是否存在?,php,mysqli,Php,Mysqli,如果没有这样的表,我想按应用程序创建表。但是第一次这么做。。。需要帮忙吗,tho //connecting... $mysqli = new mysqli($db_params['host'], $db_params['login'], $db_params['pass'], $db_params['name']); if ($mysqli->query("SHOW TABLES LIKE `products`")){ echo ' YES'; } else echo 'no';
//connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'], $db_params['pass'], $db_params['name']);
if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no';
它总是说不。阅读他们的文档?看起来你很容易做到:
CREATE TABLE IF NOT EXISTS `products`
这样,您不必首先检查表是否存在,如果不存在,您只需创建一个表即可
看起来你有一个语法错误,这可能是你的代码一直返回“否”的原因。这应该起作用:
SHOW TABLES LIKE 'products';
只需使用单引号或双引号,没有像`
那样的倒勾
表名和列名使用反引号(
`
),字符串使用单引号(”
)或双引号(”
),在这种情况下,您给出的是字符串,因此应该使用单引号或双引号。要创建不存在的表,可以使用
CREATE TABLE IF NOT EXISTS
使用PHP描述语句
if(mysql_query("DESCRIBE `table_name`")) {
// Exists
}
这个解决方案对我来说很好:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SQL query
$sql = "SHOW TABLES IN `tests`";
// perform the query and store the result
$result = $conn->query($sql);
// if the $result not False, and contains at least one row
if($result !== false) {
// if at least one table in result
if($result->num_rows > 0) {
// traverse the $result and output the name of the table(s)
while($row = $result->fetch_assoc()) {
echo '<br />'. $row['Tables_in_tests'];
}
}
else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;
$conn->close();
?>
有关完整和更多的示例,请参见源代码:您的
db_参数['pass']上缺少一个$
当然,在PHP\u my中创建了一个表“products”_admin@Albzi键入我的问题时刚好错过了它,thx。在真实代码中,我有它)尝试添加echo$mysqli->error;
并查看MySQL在说什么您必须在LIKE
的右侧有一个字符串,例如显示类似“products”的表。
。通常,请在在编写相应的PHP代码之前,请使用e命令行。这是mysql\u*
。您应该是mysqli\u*
或PDO。虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面发生更改,则只有链接的答案可能无效。-@CharlieFish,这是密码,但为什么-1;)我没有投你反对票。