如何使用 PHP 备份 MySQL 数据库

数据库备份是每个 Web 开发人员最重要的任务。
定期数据库备份可防止丢失数据的风险,并有助于在发生任何问题时恢复数据库。
因此,尽可能备份数据库是个好主意。

有多种方法可以将 MySQL 数据库备份到文件中,我们可以从托管服务器一键备份数据库。
但是,如果我们想在不登录托管服务器或者 phpMyAdmin 的情况下进行 MySQL 数据库备份,我们可以使用 PHP 从脚本中完成。
在本教程中,我们将构建一个 PHP 脚本来备份 MySQL 数据库并保存在 SQL 文件中。

使用 PHP 执行 MySQL 数据库备份

所有 PHP 代码都将在 backupDatabaseTables() 函数中组合在一起。
使用 'backupDatabaseTables()' 函数,我们可以备份数据库中的特定表或者所有表。
使用 PHP 备份 MySQL 数据库需要以下参数。

  • '$dbHost' – 必需。指定数据库的主机。
  • '$dbUsername' – 必需。指定数据库用户名。
  • '$dbPassword' – 必需。指定数据库密码。
  • '$dbName' – 必需。指定要备份的数据库。
  • '$tables' - 可选。以逗号分隔的字符串或者数组形式指定表名。省略此参数可对数据库的所有表进行备份。
<?php

function backupDatabaseTables($dbHost,$dbUsername,$dbPassword,$dbName,$tables = '*'){
    //connect & select the database
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
    //get all of the tables
    if($tables == '*'){
        $tables = array();
        $result = $db->query("SHOW TABLES");
        while($row = $result->fetch_row()){
            $tables[] = $row[0];
        }
    }else{
        $tables = is_array($tables)?$tables:explode(',',$tables);
    }
    //loop through the tables
    foreach($tables as $table){
        $result = $db->query("SELECT * FROM $table");
        $numColumns = $result->field_count;
        $return .= "DROP TABLE $table;";
        $result2 = $db->query("SHOW CREATE TABLE $table");
        $row2 = $result2->fetch_row();
        $return .= "\n\n".$row2[1].";\n\n";
        for($i = 0; $i < $numColumns; $i++){
            while($row = $result->fetch_row()){
                $return .= "INSERT INTO $table VALUES(";
                for($j=0; $j < $numColumns; $j++){
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\n",$row[$j]);
                    if (isset($row[$j])) { $return .= '"'.$row[$j].'"' ; } else { $return .= '""'; }
                    if ($j < ($numColumns-1)) { $return.= ','; }
                }
                $return .= ");\n";
            }
        }
        $return .= "\n\n\n";
    }
    //save file
    $handle = fopen('db-backup-'.time().'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

用法:
使用 PHP 中的“backupDatabaseTables()”函数生成 MySQL 数据库备份并保存在 SQL 文件中。

backupDatabaseTables('localhost','root','*','onitroad');
日期:2020-06-02 22:15:26 来源:oir作者:oir