1、建立导出类
<?php namespace App\Helper; class DbBackup{ private $table; public function __construct(){ $this->table = env('DB_DATABASE'); } public function run($file = ''){ $file = !$file ? public_path($this->table.'.mysql') : $file; $tables = \DB::select('SHOW TABLES FROM '.$this->table); $tableName = 'Tables_in_'.$this->table; $info = "-- ----------------------------\r\n"; $info .= "-- 日期:".date("Y-m-d H:i:s",time())."\r\n"; $info .= "-- 本程序不适合处理超大量数据\r\n"; $info .= "-- ----------------------------\r\n\r\n"; file_put_contents($file,$info,FILE_APPEND); //将每个表的表结构导出到文件 foreach($tables as $val){ $sql = "show create table ".$val->$tableName; $row = \DB::select($sql); $info = "-- ----------------------------\r\n"; $info .= "-- Table structure for `".$val->$tableName."`\r\n"; $info .= "-- ----------------------------\r\n"; $info .= "DROP TABLE IF EXISTS `".$val->$tableName."`;\r\n"; $temp = 'Create Table'; $sqlStr = $info.$row[0]->$temp.";\r\n\r\n"; //追加到文件 file_put_contents($file,$sqlStr,FILE_APPEND); } //将每个表的数据导出到文件 foreach($tables as $val){ $sql = "select * from ".$val->$tableName; $res = \DB::select($sql); //如果表中没有数据,则继续下一张表 if(count($res)<1) continue; // $info = "-- ----------------------------\r\n"; $info .= "-- Records for `".$val->$tableName."`\r\n"; $info .= "-- ----------------------------\r\n"; file_put_contents($file,$info,FILE_APPEND); //读取数据 foreach ($res as $key => $value) { $sqlStr = "INSERT INTO `".$val->$tableName."` VALUES ("; $sqlTemp = ''; foreach(get_object_vars($value) as $v){ $sqlTemp = !$sqlTemp ? "'".$v ."'" : $sqlTemp . ',\''.$v."'"; } $sqlStr = $sqlStr . $sqlTemp .");\r\n"; file_put_contents($file,$sqlStr,FILE_APPEND); } file_put_contents($file,"\r\n",FILE_APPEND); } return $file; } }
2、执行导出
use App\Helper\DbBackup; public function backup(){ $dir = public_path('upload/backup/'); if(!is_dir($dir)) mkdir($dir); $file_name = date('Y-m-d').'.sql'; $file_path = $dir.$file_name; $backup = new DbBackup(); $backup->run($file_path); //下面为下载sql文件 header('Content-type: application/sql'); header("Content-Disposition: attachment; filename=\"{$file_name}\""); readfile($file_path); }
本帖已被设为精华帖!