匯出資料為 CSV
<?php
function exportToCsv($host, $db, $user, $pass, $table, $sql) {
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) die('連線失敗: ' . mysqli_connect_error());
$result = mysqli_query($conn, $sql);
if (!$result) die('查詢錯誤: ' . mysqli_error($conn));
$fields = mysqli_num_fields($result);
$csv = '';
// 標題列
for ($i = 0; $i < $fields; $i++) {
$meta = mysqli_fetch_field_direct($result, $i);
$csv .= '"' . $meta->name . '"' . ($i < $fields-1 ? ',' : "\n");
}
// 資料列
while ($row = mysqli_fetch_row($result)) {
for ($i = 0; $i < $fields; $i++) {
$val = $row[$i] === null ? 'NULL' : $row[$i];
$csv .= '"' . str_replace('"', '""', $val) . '"' . ($i < $fields-1 ? ',' : "\n");
}
}
mysqli_free_result($result);
mysqli_close($conn);
return $csv;
}
// 使用範例
$csv = exportToCsv('localhost', 'project', 'root', '', 'tb_project_dvp', 'SELECT * FROM tb_project_dvp');
file_put_contents('export.csv', $csv);
?>
從 CSV 匯入資料
<?php
function importFromCsv($host, $db, $user, $pass, $table, $csvPath) {
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) die('連線失敗: ' . mysqli_connect_error());
$handle = fopen($csvPath, 'r');
if (!$handle) die('無法開啟 CSV');
// 讀取標題
$header = fgetcsv($handle);
$colCount = count($header);
$placeholders = implode(',', array_fill(0, $colCount, '?'));
$columns = implode(',', array_map(fn($c) => "`$c`", $header));
$stmt = mysqli_prepare($conn, "INSERT INTO `$table` ($columns) VALUES ($placeholders)");
mysqli_stmt_bind_param($stmt, str_repeat('s', $colCount), ...array_fill(0, $colCount, ''));
while (($row = fgetcsv($handle)) !== false) {
if (empty($row[0])) continue; // 跳過空 ID
mysqli_stmt_bind_param($stmt, str_repeat('s', $colCount), ...$row);
mysqli_stmt_execute($stmt);
}
fclose($handle);
mysqli_stmt_close($stmt);
mysqli_close($conn);
return 'OK';
}
?>
前端表單提交範例
<form method="post" action="import.php" enctype="multipart/form-data">
<input type="file" name="csv_file" accept=".csv" required>
<input type="hidden" name="table" value="tb_project_dvp">
<button type="submit">匯入</button>
</form>
安全與效能建議
- 使用預處理語句防 SQL 注入。
- 大量匯入時考慮
LOAD DATA INFILE(需檔案權限)或批次 INSERT(每 500-1000 筆 commit)。
- 驗證 CSV 結構(欄位數、型別)再匯入。
- 記錄匯入日誌(時間、筆數、錯誤)。
- 生產環境建議使用 ETL 工具或資料庫原生複製功能。