繁体   English   中英

如何使用php备份mysql数据库

[英]how to take backup of mysql database using php

当我点击链接时,我需要使用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";
}


?>

我使用这个脚本作为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);

 ?>

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

 <?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;
?>

如果你将--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可能不正确,就像你做成功的指标一样,而是使用这个表格..

  system ( string $command, &$return_var);

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

您的代码可能如下所示:

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

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

我改变了一点来支持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;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM