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

前端 未结 12 1607
小鲜肉
小鲜肉 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:40
    <?php 
    $connection = mysqli_connect("localhost","root","","php_sample_login_register"); 
    
    if ($connection){
            echo "DB is Connected <br>";
            $sql = "CREATE TABLE user(
                id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
                name VARCHAR(255)NOT NULL,
                email VARCHAR(255)NOT NULL,
                password VARCHAR(255) NOT NULL
                );";
            if(mysqli_query($connection,$sql)) {
                echo "Created user table";
            } else{
                echo "User table already exists";
            }
        } else {
            echo "error : DB isnot connected";
        } ?>
    
    0 讨论(0)
  • 2020-12-02 13:41

    DO NOT USE MYSQL ANY MORE. If you must use mysqli but PDO is best:

    $pdo = new PDO($dsn, $username, $pdo); // proper PDO init string here
    if ($pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name'")->fetch()) // table exists.
    
    0 讨论(0)
  • 2020-12-02 13:42

    You can use many different queries to check if a table exists. Below is a comparison between several:

    mysql_query('select 1 from `table_name` group by 1'); or  
    mysql_query('select count(*) from `table_name`');
    
    mysql_query("DESCRIBE `table_name`");  
    70000   rows: 24ms  
    1000000 rows: 24ms  
    5000000 rows: 24ms
    
    mysql_query('select 1 from `table_name`');  
    70000   rows: 19ms  
    1000000 rows: 23ms  
    5000000 rows: 29ms
    
    mysql_query('select 1 from `table_name` group by 1'); or  
    mysql_query('select count(*) from `table_name`');  
    70000   rows: 18ms  
    1000000 rows: 18ms  
    5000000 rows: 18ms  
    

    These benchmarks are only averages:

    0 讨论(0)
  • 2020-12-02 13:44

    Even faster than a bad query:

    SELECT count((1)) as `ct`  FROM INFORMATION_SCHEMA.TABLES where table_schema ='yourdatabasename' and table_name='yourtablename';
    

    This way you can just retrieve one field and one value. .016 seconds for my slower system.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-02 13:48
    // Select 1 from table_name will return false if the table does not exist.
    $val = mysql_query('select 1 from `table_name` LIMIT 1');
    
    if($val !== FALSE)
    {
       //DO SOMETHING! IT EXISTS!
    }
    else
    {
        //I can't find it...
    }
    

    Admittedly, it is more Pythonic than of the PHP idiom, but on the other hand, you don't have to worry about dealing with a copious amount of extra data.

    Edit

    So, this answer has been marked down at least twice as of the time I am writing this message. Assuming that I had made some gargantuan error, I went and I ran some benchmarks, and this is what I found that my solution is over 10% faster than the nearest alternative when the table does not exist, and it over 25% faster when the table does exist:

    :::::::::::::::::::::::::BEGINNING NON-EXISTING TABLE::::::::::::::::::::::::::::::
    23.35501408577 for bad select
    25.408507823944 for select from schema num rows -- calls mysql_num_rows on select... from information_schema.
    25.336688995361 for select from schema fetch row -- calls mysql_fetch_row on select... from information_schema result
    50.669058799744 for SHOW TABLES FROM test
    :::::::::::::::::::::::::BEGINNING EXISTING TABLE::::::::::::::::::::::::::::::
    15.293519973755 for good select
    20.784908056259 for select from schema num rows
    21.038464069366 for select from schema fetch row
    50.400309085846 for SHOW TABLES FROM test
    

    I tried running this against DESC, but I had a timeout after 276 seconds (24 seconds for my answer, 276 to fail to complete the description of a non existing table).

    For good measure, I am benchmarking against a schema with only four tables in it and this is an almost fresh MySQL install (this is the only database so far). To see the export, look here.

    AND FURTHERMORE

    This particular solution is also more database independent as the same query will work in PgSQL and Oracle.

    FINALLY

    mysql_query() returns FALSE for errors that aren't "this table doesn't exist".

    If you need to guarantee that the table doesn't exist, use mysql_errno() to get the error code and compare it to the relevant MySQL errors.

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