針對單表備份需求,本文提供 PHP 函數 datatosql(),動態讀取表結構與資料,產出可直接執行的完整 SQL 腳本(含 DROP TABLE IF EXISTS、CREATE TABLE、批次 INSERT)。
<?php
function datatosql($table) {
global $db; // 假設 $db 為資料庫連線物件(mysqli/PDO)
// 1. 取得建表 SQL
$result = $db->query("SHOW CREATE TABLE `$table`");
$row = $db->fetch_array($result);
$tableDump = "DROP TABLE IF EXISTS `$table`;\n";
$tableDump .= $row[1] . ";\n\n"; // Create Table 陳述式
// 2. 讀取所有資料
$rows = $db->query("SELECT * FROM `$table`");
$numFields = $db->num_fields($rows);
$numRows = $db->num_rows($rows);
// 3. 產生 INSERT 陳述式
while ($row = $db->fetch_array($rows)) {
$tableDump .= "INSERT INTO `$table` VALUES(";
$comma = "";
for ($i = 0; $i < $numFields; $i++) {
$tableDump .= $comma . "'" . mysqli_real_escape_string($db, $row[$i]) . "'";
$comma = ",";
}
$tableDump .= ");\n";
}
$tableDump .= "\n";
return $tableDump;
}
?>
SHOW CREATE TABLE 取得完整 DDL(含引擎、字符集、索引)。mysqli_real_escape_string 防止特殊字元破壞 SQL。INSERT,適合中小表;大表建議 mysqldump 或分批處理。.sql 檔或管線導入。// 使用 PDO 預處理 + 交易批次
$stmt = $pdo->prepare("INSERT INTO `$table` VALUES (".str_repeat('?,', $numFields-1)."?)");
$pdo->beginTransaction();
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$stmt->execute($row);
if ($count++ % 1000 === 0) $pdo->commit(); // 分批提交
}
$pdo->commit();