MySQLi Table Exists

后端 未结 5 409
無奈伤痛
無奈伤痛 2021-01-15 00:33

In PHP, what would be the best way of seeing if a table exists?

This is what I am using so far

public function TableExists($table) {
    $res = $thi         


        
相关标签:
5条回答
  • 2021-01-15 01:09

    Colin has the right solution -- to use SHOW TABLES LIKE. Here is what it would look like using your code:

    public function TableExists($table) {
      $res = $this->Query("SHOW TABLES LIKE $table");
      return mysql_num_rows($res) > 0;
    }
    
    0 讨论(0)
  • 2021-01-15 01:09
    $con = mysqli_connect($hostname,$username,$password,$database);
    
    if(mysqli_num_rows(mysqli_query($con,"SHOW TABLES LIKE 'accman'"))) {
      echo "DB EXIST";
    } else {
      echo "DB Not Exist";
    }
    
    0 讨论(0)
  • 2021-01-15 01:18

    What you posted is going to throw an error if the table doesn't exist. Try this instead:

    SHOW TABLES LIKE 'tablename';
    

    And ensure that you get exactly one row back.

    0 讨论(0)
  • 2021-01-15 01:21

    For seeing, if [table name] exist

    SELECT COUNT(*)
    FROM information_schema.tables 
    WHERE table_schema = '[database name]' 
    AND table_name = '[table name]';
    
    0 讨论(0)
  • 2021-01-15 01:23

    An alternative to the SHOW TABLES approach from other answers is using the INFORMATION_SCHEMA like this:

    SELECT COUNT(*)
      FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'your_database_name' AND TABLE_NAME = 'tablename';
    
    0 讨论(0)
提交回复
热议问题