如何使用PHP从SQL文件中恢复MySQL数据库

通常,PHPMyAdmin的导入部分用于从SQL文件导入或者恢复数据库。
与phpmyadmin一样,有各种选项可用于恢复MySQL数据库的表。
要在数据库中导入SQL文件,我们需要登录托管服务器或者PHPMyAdmin。
此外,我们可以从PHP脚本还原数据库,而无需登录托管服务器或者PHPMyAdmin。

当我们希望允许用户从Web应用程序还原数据库时,从PHP脚本还原数据库非常有用。
需要备份数据库的备份,以便在MySQL数据库中导入表。
在本教程中,我们将展示如何使用PHP从SQL文件导入和恢复数据库。
我们的简单PHP脚本有助于从SQL文件恢复MySQL数据库。

使用PHP恢复MySQL数据库

为了更好的可用性,所有PHP代码都被分组在“restoreDatabaseTables()”函数中。
使用PHP中的RestoredAtabasetables()函数,我们可以从.sql文件还原数据库中的表。
需要使用PHP恢复MySQL数据库所需的以下参数。

  • '$dbhost' - 必填。指定数据库的主机。
  • '$dbusame' - 必填。指定数据库用户名。
  • '$dbpassword' - 必填。指定数据库密码。
  • '$dbname' - 必填。指定要备份的数据库。
  • '$filepath' - 必填。指定从表将要恢复表的SQL文件的路径。
/**
 * @function    restoreDatabaseTables
 * @author      onitroad
 * @link        http://www.onitroad.com
 * @usage       Restore database tables from a SQL file
 */
function restoreDatabaseTables($dbHost, $dbUsername, $dbPassword, $dbName, $filePath){
    //Connect & select the database
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
    //Temporary variable, used to store current query
    $templine = '';

    //Read in entire file
    $lines = file($filePath);

    $error = '';

    //Loop through each line
    foreach ($lines as $line){
        //Skip it if it's a comment
        if(substr($line, 0, 2) == '--' || $line == ''){
            continue;
        }

        //Add this line to the current segment
        $templine .= $line;

        //If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';'){
            //Perform the query
            if(!$db->query($templine)){
                $error .= 'Error performing query "' . $templine . '": ' . $db->error . '<br /><br />';
            }

            //Reset temp variable to empty
            $templine = '';
        }
    }
    return !empty($error)?$error:true;
}

用法:
在PHP中使用“restoredatabasetables()”函数从SQL文件还原MySQL数据库。

$dbHost     = 'localhost';
$dbUsername = 'root';
$dbPassword = 'root';
$dbName     = 'databaseName';
$filePath   = 'files/yourMysqlBackupFile.sql';
restoreDatabaseTables($dbHost, $dbUsername, $dbPassword, $dbName, $filePath);
日期:2020-06-02 22:15:59 来源:oir作者:oir