首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 判斷 MySQL 資料表是否存在的三種方法

     編輯:PHP 綜合知識

方法一:查詢 SHOW TABLES 並陣列比對

function table_exists_v1($conn, $table) {
    $result = mysqli_query($conn, "SHOW TABLES");
    $tables = [];
    while ($row = mysqli_fetch_row($result)) $tables[] = $row[0];
    return in_array($table, $tables);
}

優點:相容舊版 MySQL。缺點:需撈取所有表名,大資料庫效能差。

方法二:使用 information_schema(推薦)

function table_exists_v2($conn, $db, $table) {
    $sql = "SELECT 1 FROM information_schema.TABLES 
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'ss', $db, $table);
    mysqli_stmt_execute($stmt);
    return (bool) mysqli_stmt_fetch($stmt);
}

優點:精確、效能好、支援預處理防注入、可跨資料庫查詢。

方法三:嘗試 SELECT 1 捕獲錯誤(不推薦)

function table_exists_v3($conn, $table) {
    $result = @mysqli_query($conn, "SELECT 1 FROM `$table` LIMIT 1");
    return $result !== false; // 失敗代表不存在或權限不足
}

缺點:無法區分「表不存在」與「權限不足/語法錯誤」,且會產生錯誤日誌噪音。

PDO 通用寫法

function table_exists_pdo(PDO $pdo, $db, $table) {
    $stmt = $pdo->prepare(
        "SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME=?"
    );
    $stmt->execute([$db, $table]);
    return (bool) $stmt->fetchColumn();
}

結語

強烈建議使用 information_schema + 預處理語句(方法二),兼顧安全、效能與準確性。避免使用 SHOW TABLES 全表掃描或 SELECT 試錯法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved