【问题标题】:PHP PDO check if a table with specific name exists in mySQL databasePHP PDO 检查 mySQL 数据库中是否存在具有特定名称的表
【发布时间】:2012-08-07 17:17:50
【问题描述】:

以下代码检查数据库中的表。

function checkdbexists(){
    global $krdb;
    return $krdb->query("show tables");
}

我们想检查一个名为“systems”的表是否存在,如果存在则返回 1,如果不存在则返回 null 或 0。

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    你可以使用

    array_search('system',$krb->query('show tables')->fetch())!==false;
    

    【讨论】:

    • 太棒了。 6 分钟内完美接受
    【解决方案2】:
    select 1
    from information_schema.tables
    where table_name = 'systems'
    limit 1
    

    【讨论】:

    • ...或者如果你想返回 0 如果它不存在你可以做SELECT IF((SELECT 1 FROM information_schema.tables WHERE table_name = 'systems') = 1, 1, 0) AS exists
    【解决方案3】:
    $db_tables = array_keys($pdo->query('show tables')->fetchAll (PDO::FETCH_GROUP));
    
    if(in_array('myTable', $db_tables)) 
    { 
        print "myTable exist"; 
    } 
    

    【讨论】:

    • 奇怪的是,此页面上的所有其他方法都对我不起作用,但这个方法可以
    猜你喜欢
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2013-10-15
    • 2017-11-07
    • 1970-01-01
    • 2012-01-26
    • 2010-12-31
    • 1970-01-01
    相关资源
    最近更新 更多