PHP backup and restore MySQL database code
- 2020-03-31 21:27:45
- OfStack
Here's the code:
1. Backup the database and download to the local [db_backup.php]
Restore database [db_restore.php]
1. Backup the database and download to the local [db_backup.php]
<?php
//Set the SQL file to save the file name
$filename=date("Y-m-d_H-i-s")."-".$cfg_dbname.".sql";
//The saved file name
header("Content-disposition:filename=".$filename);
header("Content-type:application/octetstream");
header("Pragma:no-cache");
header("Expires:0");
//Gets the current page file path, and the SQL file is exported to this folder
$tmpFile = (dirname(__FILE__))."\".$filename;
//Export the database with the MySQLDump command
exec("mysqldump -u$cfg_dbuser -p$cfg_dbpwd --default-character-set=utf8 $cfg_dbname > ".$tmpFile);
$file = fopen($tmpFile, "r"); //Open the file
echo fread($file,filesize($tmpFile));
fclose($file);
exit;
?>
Restore database [db_restore.php]
<form id="form1" name="form1" method="post" action="">
The database SQL File 】 : <input id="sqlFile" name="sqlFile" type="file" />
<input id="submit" name="submit" type="submit" value=" reduction " />
</form>
<?php
//My database information is stored in config. PHP file, so load this file, if yours is not stored in this file, comment line;
require_once((dirname(__FILE__).'/../../include/config.php'));
if ( isset ( $_POST['sqlFile'] ) )
{
$file_name = $_POST['sqlFile']; //The SQL file name to import
$dbhost = $cfg_dbhost; //Database host name
$dbuser = $cfg_dbuser; //Database user name
$dbpass = $cfg_dbpwd; //Database password
$dbname = $cfg_dbname; //The database name
set_time_limit(0); //Set the timeout time to 0 to indicate that it has been executed. When PHP is invalid in safe mode, it may cause the import to time out, requiring a staged import
$fp = @fopen($file_name, "r") or die(" Can't open SQL file $file_name");//Open the file
mysql_connect($dbhost, $dbuser, $dbpass) or die(" Can't Connect to database$dbhost");//Connect to database
mysql_select_db($dbname) or die (" Can't Open database$dbname");//Open database
echo "<p> Emptying the database , Please wait a moment ....<br>";
$result = mysql_query("SHOW tables");
while ($currow=mysql_fetch_array($result))
{
mysql_query("drop TABLE IF EXISTS $currow[0]");
echo " Clean the data table [ ".$currow[0]." 】 success! <br>";
}
echo "<br> Congratulations on cleaning up. MYSQL successful <br>";
echo " An import database operation is being performed <br>";
//Import the MySQL command to the database
exec("mysql -u$cfg_dbuser -p$cfg_dbpwd $cfg_dbname < ".$file_name);
echo "<br> Import complete! ";
mysql_close();
}
?>