Check if a database table exists using PHP/PDO

前端 未结 13 1780
长情又很酷
长情又很酷 2020-12-14 16:08

I want to check if a table with a specific name exists in a database I\'ve connected to using PHP and PDO.

It has to work on all database backends, like MySQL, SQLi

相关标签:
13条回答
  • 2020-12-14 16:43

    This seems to work at least with SQLite3 without exceptions, etc:

            $select =
                "SELECT CASE WHEN EXISTS (SELECT * FROM SQLITE_MASTER WHERE TYPE = 'table' AND NAME = :tableName) THEN 1 ELSE 0 END AS TABLE_EXISTS;";
    
    0 讨论(0)
  • 2020-12-14 16:44

    Before I go on, I do realise this is a MySQL-specific solution.

    While all the solutions mentioned here may work, I (personally) like to keep PDO from throwing exceptions (personal preference, that's all).

    As such, I use the following to test for table creation instead:

    SHOW TABLES LIKE 'some_table_of_mine';
    

    There's no error state generated if the table doesn't exist, you simply get a zero resultset. Works fast and consistently for me.

    0 讨论(0)
  • 2020-12-14 16:48

    If you have other major actions to do within the same statement, you can use the e->errorInfo

    try{                
        //Your major statements here
    }
    catch(PDOException $e){
        if($e->errorInfo[1] == 1146){
            //when table doesn't exist
        }      
    }
    
    0 讨论(0)
  • 2020-12-14 16:52

    I do a few things in my web apps with CodeIgniter to check that the database exists (and is useful), any of these can work:

    @$this->load->database();
    $v = @$this->db->version()
    $tables = @$this->db->list_tables();
    

    Adding the @ will suppress errors if you have them enabled in your PHP setup, and checking the results of version() and list_tables() can be used to not only determine if your DB is around (but that it's sane too).

    0 讨论(0)
  • 2020-12-14 16:58

    You might be able to avoid having to rely on an error by using a query along the lines of "SHOW TABLES LIKE 'your_table'" and then counting the rows. I've been using this method successfully with MySQL and PDO but have yet to test it with other DBs

    0 讨论(0)
  • 2020-12-14 17:00

    Do:

    select 1 from your_table
    

    and then catch the error. If you don't get any error, but resultset with one column containing "1", then the table exists.

    0 讨论(0)
提交回复
热议问题