81 lines
2.7 KiB
PHP
81 lines
2.7 KiB
PHP
<?php
|
|
class Mysqldump{
|
|
public function back(){
|
|
$to_file_name="send.sql";
|
|
if(!file_exists($to_file_name)){
|
|
touch($to_file_name);
|
|
chmod($to_file_name,0777,true);
|
|
}
|
|
//数据库中有哪些表
|
|
$sql='SHOW TABLES';
|
|
$tables= self::selectSql($sql);
|
|
//dd($result);die;
|
|
$tablelist=array();
|
|
foreach($tables as $v){
|
|
foreach($v as $vv){
|
|
$tablelist[]=$vv;
|
|
}
|
|
|
|
}
|
|
echo "正在备份,请耐心等待...<br/>";
|
|
$info = "-- ----------------------------\r\n";
|
|
$info .= "-- 日期:".date("Y-m-d H:i:s",time())."\r\n";
|
|
|
|
$info .= "-- ----------------------------\r\n\r\n";
|
|
file_put_contents($to_file_name,$info,FILE_APPEND);
|
|
//将每个表的表结构导出到文件
|
|
foreach($tablelist as $val){
|
|
$res = self::selectSql('show create table '.$val);
|
|
foreach($res as $v){
|
|
$newres=$v['Create Table'];
|
|
}
|
|
|
|
$info = "-- ----------------------------\r\n";
|
|
$info .= "-- Table structure for `".$val."`\r\n";
|
|
$info .= "-- ----------------------------\r\n";
|
|
$info .= "DROP TABLE IF EXISTS `".$val."`;\r\n";
|
|
$sqlStr = $info.$newres.";\r\n\r\n";
|
|
//追加到文件
|
|
file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
|
|
}
|
|
|
|
//将每个表的数据导出到文件
|
|
foreach($tablelist as $val){
|
|
//$sql = "select * from ".$val;
|
|
$res =self::selectSql('select * from '.$val);
|
|
|
|
//如果表中没有数据,则继续下一张表
|
|
if(count($res)<1) continue;
|
|
//
|
|
$info = "-- ----------------------------\r\n";
|
|
$info .= "-- Records for `".$val."`\r\n";
|
|
$info .= "-- ----------------------------\r\n";
|
|
file_put_contents($to_file_name,$info,FILE_APPEND);
|
|
//读取数据
|
|
|
|
foreach($res as $v){
|
|
$sqlstr="INSERT INTO `".$val."` VALUES (";
|
|
foreach($v as $vv){
|
|
//将数据中的单引号转义,否则还原时会出错
|
|
$newvv= str_replace("'","\'",$vv);
|
|
$sqlstr .="'".$newvv."', ";
|
|
}
|
|
//去掉最后一个逗号和空格
|
|
$sqlstr = substr($sqlstr,0,strlen($sqlstr)-2);
|
|
$sqlstr .= ");\r\n";
|
|
file_put_contents($to_file_name,$sqlstr,FILE_APPEND);
|
|
}
|
|
|
|
|
|
file_put_contents($to_file_name,"\r\n",FILE_APPEND);
|
|
}
|
|
|
|
echo "OK!";
|
|
|
|
}
|
|
|
|
public function selectSql($sql){
|
|
$result=Yii::$app->getDb()->createCommand($sql)->queryAll();
|
|
return $result;
|
|
}
|
|
} |