【问题标题】:Checking that a table exists on MySQL [duplicate]检查 MySQL 上是否存在表 [重复]
【发布时间】:2013-08-06 18:43:50
【问题描述】:

我正在尝试检查表是否存在,如果存在则执行一些操作。我不断收到一个错误,告诉我该表不存在,而不是完成我的检查。代码如下:

$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 语句似乎无法确定表是否存在。我还能做什么?

【问题讨论】:

    标签: php mysql


    【解决方案1】:

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

    SELECT 
      * 
    FROM
      information_schema 
    WHERE TABLE_NAME = "$table_array" 
    

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

    【讨论】:

    • 那...是...太棒了...并且说我将该表作为 phpMyAdmin 侵入式表的一部分... :)
    • 我的名字是 Alfred Salketer Arengard(是的,我知道...),我“同意”这个答案...@jaczes ;)
    • 好的,可以,但是如何测试它是否为空?这就是我所拥有的: $tableExists = $db->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?"); $tableExists->execute(array($table_array)); if(!is_null($tableExist)) {
    • 你可以做Select COUNT(*) from ... -> 1 和更多 = 有桌子,0 = 没有桌子
    • 对不起,我想我没有正确解释自己。如何检查查询以检查表是否存在的结果是否为正?
    【解决方案2】:
    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

    【讨论】:

    • 谢谢,我搜索并没有找到其他答案
    • 您知道根据上面的更新如何检查表是否存在吗?
    【解决方案3】:

    试试这个:

    select case when (select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME='offices') = 1 then 'exists' else 'does not exist' end
    

    【讨论】:

    • 嗨,你能再解释一下吗?这就是我现在所拥有的,我只是不知道如何测试查询的结果是否有效(表存在)。 $tableExists = $db->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?"); $tableExists->execute(array($table_array)); if(!is_null($tableExist)) {//做代码}
    【解决方案4】:

    试试这个:

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

    希望这对你有用。

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 2014-03-15
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多