php 检查MySQL表是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9008299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if MySQL table exists or not
提问by Mohammad Saberi
Possible Duplicate:
MySQL check if a table exists without throwing an exception
可能的重复:
MySQL 在不抛出异常的情况下检查表是否存在
I have a dynamic mysql query builder in my project that creates select queries from different tables.
I need to check if the current processing table exists or not.
Imagine that my tables are table1, table2, and table3. My code is something like this:
我的项目中有一个动态 mysql 查询构建器,它可以从不同的表中创建选择查询。
我需要检查当前处理表是否存在。
假设我的表是 table1、table2 和 table3。我的代码是这样的:
<?php
for($i = 1 ; $i <= 3 ; $i++) {
$this_table = 'table'.$i;
$query = mysql_query("SELECT * FROM $this_table");
// ...
}
?>
How can I do this check (Please tell me the simplest way).
我该如何做这个检查(请告诉我最简单的方法)。
回答by afuzzyllama
Updated mysqli version:
更新了 mysqli 版本:
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
echo "Table exists";
}
}
else {
echo "Table does not exist";
}
Original mysql version:
原来的mysql版本:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
Referenced from the PHP docs.
引用自PHP 文档。
回答by bowlerae
Taken from another post
取自另一个帖子
$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;
回答by Timur
$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
$tablesExists[] = $row[0];
}
回答by Zulkhaery Basrul
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
回答by Ionel Lupu
You can try this
你可以试试这个
$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());
or this
或这个
$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");
or this
或这个
$query = mysql_query("SELECT * FROM $this_table");
if(!$query)
echo "The ".$this_table." does not exists";
Hope it helps!
希望能帮助到你!
回答by Michael Dillon
Use this query and then check the results.
使用此查询,然后检查结果。
$query = 'show tables like "test1"';
回答by Castilho
MySQL way:
MySQL方式:
SHOW TABLES LIKE 'pattern';
SHOW TABLES LIKE 'pattern';
There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php
还有一个已弃用的 PHP 函数用于列出所有数据库表,请查看 http://php.net/manual/en/function.mysql-list-tables.php
Checkout that link, there are plenty of useful insight on the comments over there.
查看该链接,那里的评论有很多有用的见解。