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

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

    125 microsecond table exists check

    .000125 sec. (125µs)

    mysql_unbuffered_query("SET profiling = 1");  // for profiling only
    
    @mysql_unbuffered_query("SELECT 1 FROM `table` LIMIT 1 ");
    if (mysql_errno() == 1146){
    
     // NO EXISTING TABLE CODE GOES HERE
    
    }
    elseif(mysql_errno() > 0){
    
      echo mysql_error();    
    
    }
    
    $results = mysql_query("SHOW PROFILE");  // for profiling only
    

    Execution time, measured using mysql profiling, when a table exists, or not, is about .000125 sec. (125µs)

    The LIMIT 1 is important for speed. This minimizes the Sorting Result and Sending Data query State times. And table size is not a factor.

    I always use an unbuffered query when no results are required.

    PROFILE RESULTS WHEN TABLE DOES NOT EXIST

    QUERY STATE           SECONDS   
    --------------------  -------
    starting              0.000025  
    checking permissions  0.000006  
    Opening tables        0.000065  
    query end             0.000005  
    closing tables        0.000003  
    freeing items         0.000013  
    logging slow query    0.000003  
    cleaning up           0.000003  
    TOTAL                 0.000123  <<<<<<<<<<<< 123 microseconds
    

    WHEN TABLE EXISTS

    QUERY STATE           SECONDS   
    --------------------  -------
    starting              0.000024
    checking permissions  0.000005
    Opening tables        0.000013
    System lock           0.000007
    init                  0.000006
    optimizing            0.000003
    statistics            0.000009
    preparing             0.000008
    executing             0.000003
    Sending data          0.000019
    end                   0.000004
    query end             0.000004
    closing tables        0.000006
    freeing items         0.00001
    logging slow query    0.000003
    cleaning up           0.000003
    TOTAL                 0.000127 <<<<<<<<<<<< 127 microseconds
    

提交回复
热议问题