<?php
// 设置页面执行时间
set_time_limit(0);
// 设置内存无限制
ini_set('memory_limit', '-1');
class BackupMySQL {
private $DB_HOST = '127.0.0.1'; // 数据库主机名
private $DB_USER = 'root'; // 数据库用户名
private $DB_PASS = 'pwd'; // 数据库密码
private $DB_NAME = 'dbname'; // 数据库名
// 备份文件保存路径
private $backup_path = './backup/';
function __construct($backup_path,$dbname){
$this->backup_path = $backup_path;
$this->DB_NAME = $dbname;
}
// 备份数据库
function backup(){
$mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
if(mysqli_connect_errno()){
throw new Exception("Connect failed: ".mysqli_connect_error());
}
$mysqli->query("set names utf8");
$tables = array();
$result = $mysqli->query("show tables");
while($row = $result->fetch_row()){
$tables[] = $row[0];
}
$mysqli->query("SET FOREIGN_KEY_CHECKS=0");
$sql = '';
foreach($tables as $table){
$result = $mysqli->query("select * from ".$table);
$num_fileds = $result->field_count;
$num_rows = $mysqli->affected_rows;
$sql .= 'DROP TABLE IF EXISTS '.$table.';';
$mysql_query = $mysqli->query('show create table '.$table);
if (empty($mysql_query)) {
continue;
}
$row2 = $mysql_query->fetch_row();
$sql .= "\n\n".$row2[1].";\n\n";
for($i = 0; $i < $num_rows; $i++){
$row = $result->fetch_row();
$sql .= "INSERT INTO ".$table." VALUES(";
for($j = 0; $j < $num_fileds; $j++){
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("/\n/i","\\n",$row[$j]);
if(isset($row[$j])){
$sql .= '"'.$row[$j].'"';
}
else{
$sql.= '""';
}
if($j < ($num_fileds - 1)){
$sql .= ',';
}
}
$sql .= ");\n";
}
$sql .= "\n\n\n";
}
$mysqli->query("SET FOREIGN_KEY_CHECKS=1");
$filename = $this->backup_path.$this->DB_NAME.".sql";
mysqli_close($mysqli);
if(file_put_contents($filename, $sql)){
return true;
}
else{
return false;
}
}
}
//查看所有的数据库信息
$mysqli = new mysqli('127.0.0.1', 'root', 'pwd', 'dbname');
if(mysqli_connect_errno()){
throw new Exception("Connect failed: ".mysqli_connect_error());
}
$mysqli->query("set names utf8");
$databases = array();
$result = $mysqli->query("show databases");
while($row = $result->fetch_row()){
$databases[] = $row[0];
}
//关闭数据库连接
mysqli_close($mysqli);
foreach ($databases as $key => $value) {
$backup = new BackupMySQL('./backup/',$value);
try {
$backup->backup();
echo $value.'数据库已备份=>';
} catch (Exception $e) {
echo '备份失败:'.$e->getMessage();
}
}
echo "success";
网友评论