1. Giới thiệu hàm xuất CSDL thành file .sql
Tạo file backup.php và chép nội dung sau vào:
<?php
function export_tables($host, $user, $pass, $name, $tables = false, $backup_name = false) {
set_time_limit(3000);
$mysqli = new mysqli($host, $user, $pass, $name);
$mysqli->query("SET NAMES 'utf8'");
$target_tables = [];
$queryTables = $mysqli->query("SHOW TABLES");
while ($row = $queryTables->fetch_row()) {
$target_tables[] = $row[0];
}
if ($tables !== false) {
$target_tables = array_intersect($target_tables, $tables);
}
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\nSET time_zone = \"+00:00\";\n";
$content .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n";
$content .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n";
$content .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n";
$content .= "/*!40101 SET NAMES utf8 */;\n\n--\n-- Database: `{$name}`\n--\n\n";
foreach ($target_tables as $table) {
if (empty($table)) continue;
$result = $mysqli->query("SELECT * FROM `$table`");
$fields_amount = $result->field_count;
$rows_num = $mysqli->affected_rows;
$res = $mysqli->query("SHOW CREATE TABLE `$table`");
$TableMLine = $res->fetch_row();
$content .= "\n\n" . $TableMLine[1] . ";\n\n";
$st_counter = 0;
while ($row = $result->fetch_row()) {
if ($st_counter % 100 === 0) $content .= "INSERT INTO `$table` VALUES\n";
$content .= "(";
for ($j = 0; $j < $fields_amount; $j++) {
$row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
$content .= isset($row[$j]) ? "\"{$row[$j]}\"" : "\"\"";
if ($j < $fields_amount - 1) $content .= ",";
}
$content .= ")";
$st_counter++;
$content .= ($st_counter % 100 === 0 || $st_counter === $rows_num) ? ";\n" : ",\n";
}
$content .= "\n";
}
$content .= "\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n";
$content .= "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n";
$content .= "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ?: "{$name}___(" . date('H-i-s_d-m-Y') . ")__rand" . rand(1, 9999999) . ".sql";
ob_get_clean();
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"{$backup_name}\"");
echo $content;
exit;
}
export_tables('localhost', 'root', '', 'database_name', false, 'backup.sql');
?>
2. Giải thích tham số hàm
export_tables('host', 'username', 'password', 'database_name', $tables, 'filename.sql');
$tables: có thể là mảng tên bảng, hoặcfalseđể backup toàn bộ$filename: tên tập tin backup đầu ra
3. Cách sử dụng
- Sao chép file
backup.phpvào thư mục gốc dự án PHP - Truy cập qua trình duyệt:
http://localhost/project/backup.php - Tập tin
.sqlsẽ được tải về tự động
Để tăng bảo mật, bạn có thể kiểm tra session, token hoặc chỉ cho phép chạy khi có điều kiện cụ thể để tránh người khác truy cập trái phép.
Kết luận
Dù đoạn mã này khá đơn giản, nhưng cực kỳ hữu dụng trong trường hợp bạn không thể dùng command line, cPanel hoặc phpMyAdmin. Đây là một thủ thuật “hồi xưa” nhưng vẫn hữu ích trong nhiều tình huống – đặc biệt khi bạn viết web PHP thuần và cần tự chủ toàn bộ quá trình backup dữ liệu.
Bình luận