How can I check if a MySQL table exists with PHP?

前端 未结 12 1649
小鲜肉
小鲜肉 2020-12-02 13:08

As simple in theory as it sounds I\'ve done a fair amount of research and am having trouble figuring this out.

How can I check if a MySQL table exists and if it does

12条回答
  •  执笔经年
    2020-12-02 13:47

    SHOW TABLES LIKE 'TableName'

    If you have ANY results, the table exists.

    To use this approach in PDO:

    $pdo         = new \PDO(/*...*/);
    $result      = $pdo->query("SHOW TABLES LIKE 'tableName'");
    $tableExists = $result !== false && $result->rowCount() > 0;
    

    To use this approach with DEPRECATED mysql_query

    $result      = mysql_query("SHOW TABLES LIKE 'tableName'");
    $tableExists = mysql_num_rows($result) > 0;
    

提交回复
热议问题