如何使用php备份mysql数据库

时间:2018-09-27 06:34:10

标签: php database mysqli

当我单击链接时,我需要使用php导出数据库的备份。我搜索了很多参考文献并创建了代码。但是,当我执行此操作时,它将显示错误。谁能帮助我获得解决方案?这是我的代码

<a href="back.php">BACKUP</a>

Back.php

<?php
include('../database.php');
   $dbhost = $_SERVER['SERVER_NAME'];
   $dbuser = 'root';
   $dbpass = '';
   $dbname='marketing';
   $backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';
   $command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass ". "$dbname | gzip > $backup_file";

   $sys=system($command);
if($sys)
{
    echo "succc";
}
else{
    echo "failed";
}


?>

4 个答案:

答案 0 :(得分:1)

我将此脚本用作CRON任务。     

// Edit this section
$dbhost = "SERVER IP OR LOCALHOST";
$dbuser = "DB USER";
$dbpass = "DB PASSWORD";
$dbname = "DB NAME ";
$message = "E-MAIL MESSAGE TEXT";

// Don't need to edit below this section

function compress($filepath) {
    $zip = new ZipArchive();
    $file=$filepath.".zip";

    if($zip->open($file,1?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE) {
        // Add the files to the .zip file
        $zip->addFile($filepath);

        // Closing the zip file
        $zip->close();
    }
 }  

 ini_set('date.timezone', 'Europe/Budapest');
 $backupfile = $dbname.'_'.date("Y-m-d_H-i", time()).'.sql';
 system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile");
 compress($backupfile);

 // Send E-mail notification
 $sendto = "NAME <E-MAIL ADDRESS>";
 $sendfrom = "NAME <E-MAIL ADDRESS>";
 $sendsubject = "SUBJECT";
 // $message="This attachment contains the backup of your database.";
 $separator = md5(time());

 // attachment name
 $filename = $backupfile.".zip";

 // Open db file
 $file = fopen( $backupfile, "r" );
 // Read the file into a variable
 $size = filesize($backupfile);
 $content = fread( $file, $size);

 //$pdfdoc is PDF generated by FPDF
 $attachment = chunk_split(base64_encode(file_get_contents($filename)));

 // Define the main headers.
 $header = "From:$sendfrom\r\n";
 $header .= "MIME-Version: 1.0\r\n";
 $header .= "Content-Type: multipart/mixed; ";
 $header .= "boundary=$separator\r\n";
 $header .= "--$num\r\n";

 // Define the message section
 $header .= "Content-Type: text/plain\r\n";
 $header .= "Content-Transfer-Encoding:8bit\r\n\n";
 $header .= "$message\r\n";
 $header .= "--$separator\r\n";

 // Define the attachment section
 $header .= "Content-Type:  application/octet-stream; ";
 $header .= "name=\"$filename\"\r\n";
 $header .= "Content-Transfer-Encoding:base64\r\n";
 $header .= "Content-Disposition:attachment; ";
 $header .= "filename=\"$filename\"\r\n\n";
 $header .= "$attachment\r\n";
 $header .= "--$separator--";

 // Send email now
 mail( $sendto, $sendsubject, "", $header );

 // Delete the SQL and ZIP file from your server
 unlink($backupfile);
 unlink($filename);

 ?>

答案 1 :(得分:1)

您可以在任务中直接使用以下代码模式

 <?php
    $dbhost = $_SERVER['SERVER_NAME'];
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'marketing';
    $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    $backupAlert = '';
    $tables = array();
    $result = mysqli_query($connection, "SHOW TABLES");
    if (!$result) {
        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
    } else {
        while ($row = mysqli_fetch_row($result)) {
            $tables[] = $row[0];
        }
        mysqli_free_result($result);

        $return = '';
        foreach ($tables as $table) {

            $result = mysqli_query($connection, "SELECT * FROM " . $table);
            if (!$result) {
                $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
            } else {
                $num_fields = mysqli_num_fields($result);
                if (!$num_fields) {
                    $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                } else {
                    $return .= 'DROP TABLE ' . $table . ';';
                    $row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
                    if (!$row2) {
                        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                    } else {
                        $return .= "\n\n" . $row2[1] . ";\n\n";
                        for ($i = 0; $i < $num_fields; $i++) {
                            while ($row = mysqli_fetch_row($result)) {
                                $return .= 'INSERT INTO ' . $table . ' VALUES(';
                                for ($j = 0; $j < $num_fields; $j++) {
                                    $row[$j] = addslashes($row[$j]);
                                    if (isset($row[$j])) {
                                        $return .= '"' . $row[$j] . '"';
                                    } else {
                                        $return .= '""';
                                    }
                                    if ($j < $num_fields - 1) {
                                        $return .= ',';
                                    }
                                }
                                $return .= ");\n";
                            }
                        }
                        $return .= "\n\n\n";
                    }

                    $backup_file = $dbname . date("Y-m-d-H-i-s") . '.sql';
                    $handle = fopen("{$backup_file}", 'w+');
                    fwrite($handle, $return);
                    fclose($handle);
                    $backupAlert = 'Succesfully got the backup!';
                }
            }
        }
    }
    echo $backupAlert;
?>

答案 2 :(得分:0)

如果将--verbose 2> output.txt添加到命令中,它将例如下面逐行地说明正在发生的事情。显然,您需要在命令后查看output.txt的内容。

-- Connecting to localhost...
-- Retrieving table structure for table users...
-- Sending SELECT query...
-- Retrieving rows...
-- Disconnecting from localhost...

您的完整命令将是:

"mysqldump --opt -h $dbhost -u $dbuser -p $dbpass --verbose 2> output.txt". "$dbname | gzip > $backup_file"

另外,像您已成功地测试$ sys一样,测试$ sys也可能是不正确的,而是使用此表格。.

  system ( string $command, &$return_var);

然后$ return将包含已执行命令(mysqldump)的返回状态,这对于测试备份的实际成功是更好的。

您的代码可能如下所示:

int $return_var;
system ($command, &$return_var);

if ($return_var ==0){
    echo "success";
}
else{
    echo "failed";
}

答案 3 :(得分:0)

我做了一些改动以支持utf8

<title><?php echo "backup MySQL data - " . $_SERVER['SERVER_NAME'] ; ?></title>
<?php 

// ref. to https://stackoverflow.com/questions/52530833/how-to-take-backup-of-mysql-database-using-php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'jackycms2019';
    $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    mysqli_set_charset($connection,"utf8");
    $backupAlert = '';
    $tables = array();
    $result = mysqli_query($connection, "SHOW TABLES");
    if (!$result) {
        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
    } else {
        while ($row = mysqli_fetch_row($result)) {
            $tables[] = $row[0];
        }
        mysqli_free_result($result);

        $return = '';
        foreach ($tables as $table) {

            $result = mysqli_query($connection, "SELECT * FROM " . $table);
            if (!$result) {
                $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
            } else {
                $num_fields = mysqli_num_fields($result);
                if (!$num_fields) {
                    $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                } else {
                    $return .= 'DROP TABLE ' . $table . ';';
                    $row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
                    if (!$row2) {
                        $backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
                    } else {
                        $return .= "\n\n" . $row2[1] . ";\n\n";
                        for ($i = 0; $i < $num_fields; $i++) {
                            while ($row = mysqli_fetch_row($result)) {
                                $return .= 'INSERT INTO ' . $table . ' VALUES(';
                                for ($j = 0; $j < $num_fields; $j++) {
                                    $row[$j] = addslashes($row[$j]);
                                    if (isset($row[$j])) {
                                        $return .= '"' . $row[$j] . '"';
                                    } else {
                                        $return .= '""';
                                    }
                                    if ($j < $num_fields - 1) {
                                        $return .= ',';
                                    }
                                }
                                $return .= ");\n";
                            }
                        }
                        $return .= "\n\n\n";
                    }

                    $backup_file = $dbname . '.sql';
                    $handle = fopen("{$backup_file}", 'w+');
                    fwrite($handle, $return);
                    fclose($handle);
                    $backupAlert = 'backup MySQL data completed !';
                }
            }
        }
    }
    echo $backupAlert;
?>