检查MySQL上是否存在表

时间:2013-08-05 22:13:37

标签: php mysql

我正在尝试检查表是否存在,如果存在则执行某些操作。我继续收到错误,告诉我该表不存在而不是完成我的支票。这是代码:

$tableExists = $db->prepare("SHOW TABLES LIKE $table_array");
$tableExists->execute();
if($tableExists->rowCount() > 0) {
   // do some code
 } else {
   echo "Unable to add because table does not exists";
}

更新: 根据以下建议,我现在执行以下操作:

$tableExists = $db->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?"); 
$tableExists->execute(array($table_array)); 
if(!is_null($tableExist)) { 
    //do something
} else {
    echo "table does not exist;
}

但是,if语句似乎无法确定表是否存在。我还能做什么?

4 个答案:

答案 0 :(得分:11)

尝试使用information_schema询问表格是否存在。像

这样的东西
SELECT 
  * 
FROM
  information_schema 
WHERE TABLE_NAME = "$table_array" 

查看information_schema所持有的所有内容,您会对其存储的有关数据库的信息感到惊喜:)

答案 1 :(得分:1)

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

参考:check if MySQL table exists or not

答案 2 :(得分:0)

试试这个:

选择大小时(从INFORMATION_SCHEMA.TABLES中选择count(*),其中TABLE_NAME ='offices')= 1然后'存在'其他'不存在'结束

答案 3 :(得分:-1)

试试这个:

select * from table_schema //this is your database name    
where table_name // your table name    
= '$table_array'

希望这适合你。