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。缺點:需撈取所有表名,大資料庫效能差。
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);
}
優點:精確、效能好、支援預處理防注入、可跨資料庫查詢。
function table_exists_v3($conn, $table) {
$result = @mysqli_query($conn, "SELECT 1 FROM `$table` LIMIT 1");
return $result !== false; // 失敗代表不存在或權限不足
}
缺點:無法區分「表不存在」與「權限不足/語法錯誤」,且會產生錯誤日誌噪音。
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 試錯法。