; 分割成多條 SQL 語句。mysql_query()(或 PDO)。<?php
$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8", 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = file_get_contents('install.sql');
$statements = array_filter(array_map('trim', explode(';', $sql)));
foreach ($statements as $stmt) {
if ($stmt) {
try {
$pdo->exec($stmt);
echo "OK: " . substr($stmt, 0, 50) . "...\n";
} catch (PDOException $e) {
echo "FAIL: " . $e->getMessage() . "\nSQL: $stmt\n";
}
}
}
echo "匯入完成";
explode(';') 會誤切。生產環境建議使用專用解析器或 mysqli_multi_query()。mysqli_multi_query() 範例:$mysqli = new mysqli('localhost', 'root', 'root', 'test');
$sql = file_get_contents('install.sql');
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) $result->free();
} while ($mysqli->next_result());
}
echo $mysqli->error ? "錯誤: $mysqli->error" : "成功";
超大 SQL 檔(>100MB)建議用命令列匯入,避免 PHP 記憶體/執行時間限制:
mysql -u root -p test < install.sql