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

前端 未结 12 1680
小鲜肉
小鲜肉 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:57

    The cleanest way to achieve this in PHP is to simply use DESCRIBE statement.

    if ( mysql_query( "DESCRIBE `my_table`" ) ) {
        // my_table exists
    }
    

    I'm not sure why others are posting complicated queries for a such a straight forward problem.

    Update

    Using PDO

    // assuming you have already setup $pdo
    $sh = $pdo->prepare( "DESCRIBE `my_table`");
    if ( $sh->execute() ) {
        // my_table exists
    } else {
        // my_table does not exist    
    }
    

提交回复
热议问题