<?php
$sqlContent = file_get_contents('backup.sql'); // 讀取整個 SQL 文件
$statements = explode(';', $sqlContent); // 按分號分割語句
foreach ($statements as $stmt) {
$stmt = trim($stmt);
if (empty($stmt)) continue; // 跳過空語句
$stmt .= ';'; // 還原分號
$result = mysqli_query($conn, $stmt); // 執行(需先建立 $conn)
if (!$result) {
error_log("SQL 執行失敗: " . mysqli_error($conn) . "\nSQL: $stmt");
}
}
?>
mysql_* 函數,生產環境必須改用 mysqli 或 PDO。explode(';') 會誤切含分號的字符串字面量,健壯方案需用正則或解析器(如 php-sql-parser)。<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle = fopen('backup.sql', 'r');
$buffer = '';
$count = 0;
$pdo->beginTransaction();
try {
while (($line = fgets($handle)) !== false) {
$buffer .= $line;
if (substr(trim($line), -1) === ';') {
$pdo->exec($buffer);
$buffer = '';
if (++$count % 100 === 0) $pdo->commit(); // 每 100 條提交一次
}
}
$pdo->commit();
echo "導入成功,共執行 $count 條語句";
} catch (PDOException $e) {
$pdo->rollBack();
echo "導入失敗: " . $e->getMessage();
}
fclose($handle);
?>
自動化安裝腳本、數據庫遷移工具、備份恢復功能等。