首页 > 解决方案 > 使用 php 将整个 mysql 数据库备份到特定文件/位置

问题描述

伙计们请告诉我要在下面的代码中添加什么来获取数据库的备份,我可以将文件保存在特定位置。现在,当我通过网络浏览器下载某些内容时,脚本要求我像往常一样保存文件。我想运行脚本并将文件 xxxx.sql 自动保存在系统中的特定位置 - 例如在 C:/backups 中没有任何交互。

代码:

<?php

// Database configuration
$host = "localhost";
$username = "test";
$password = "test";
$database_name = "test";

// Get connection object and set the charset
$conn = mysqli_connect($host, $username, $password, $database_name);
$conn->set_charset("utf8");


// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

$sqlScript = "";
foreach ($tables as $table) {

    // Prepare SQLscript for creating table structure
    $query = "SHOW CREATE TABLE $table";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);

    $sqlScript .= "\n\n" . $row[1] . ";\n\n";


    $query = "SELECT * FROM $table";
    $result = mysqli_query($conn, $query);

    $columnCount = mysqli_num_fields($result);

    // Prepare SQLscript for dumping data for each table
    for ($i = 0; $i < $columnCount; $i ++) {
        while ($row = mysqli_fetch_row($result)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $columnCount; $j ++) {
                $row[$j] = $row[$j];

                if (isset($row[$j])) {
                    $sqlScript .= '"' . $row[$j] . '"';
                } else {
                    $sqlScript .= '""';
                }
                if ($j < ($columnCount - 1)) {
                    $sqlScript .= ',';
                }
            }
            $sqlScript .= ");\n";
        }
    }

    $sqlScript .= "\n"; 
}

if(!empty($sqlScript))
{
    // Save the SQL script to a backup file
    $backup_file_name = $database_name . '_backup_' . time() . '.sql';
    $fileHandler = fopen($backup_file_name, 'w+');
    $number_of_lines = fwrite($fileHandler, $sqlScript);
    fclose($fileHandler); 

    // Download the SQL backup file to the browser
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backup_file_name));
    ob_clean();
    flush();
    readfile($backup_file_name);
    exec('rm ' . $backup_file_name); 
}
?>

标签: phpmysqldatabase-backups

解决方案


您已经将文件保存到磁盘的某个位置,因此只需将位置更改为您想要放置的位置

if(!empty($sqlScript))
{
    $path = 'C:/my_db_backups/';

    // Save the SQL script to a backup file
    $backup_file_name = $path . $database_name . '_backup_' . time() . '.sql';

    . . .

然后删除

exec('rm ' . $backup_file_name); 

推荐阅读