备份数据库
public function beifensql(Request $request){ $table_name = $request ->get('houtai'); $DB_HOST = getenv('DB_HOST'); $DB_DATABASE = getenv('DB_DATABASE'); //从配置文件中获取数据库信息 $DB_USERNAME = getenv('DB_USERNAME'); $DB_PASSWORD = getenv('DB_PASSWORD'); $dumpfname = $DB_DATABASE . "_" . date("Y-m-d_H-i-s").".sql"; $command = "D:\\phpstudy\\PHPTutorial\\MySQL\\bin\\mysqldump --add-drop-table --host=$DB_HOST --user=$DB_USERNAME "; if ($DB_PASSWORD) $command.= "--password=". $DB_PASSWORD ." "; $command.= $DB_DATABASE." "; $command.= $table_name; $command.= " > " . $dumpfname; system($command); //将备份信息入库 $file_size = filesize($dumpfname); $times=date('Y-m-d H:i:s'); $re = DB::table('database_backups')->insert( [ 'file_name' => $dumpfname, 'file_size' => $file_size, 'backups_time' => $times, ]); if($re){ echo "<script>alert('备份成功');location.href='/'</script>"; } }
数据库恢复
/** 数据恢复 导入 */ public function huifusql($id){ header('content-type:text/html;charset=utf-8'); $results = DatabaseBackup::findOrFail($id); // dump($results); $filename=$results['file_name']; $DB_HOST = getenv('DB_HOST'); $DB_DATABASE = getenv('DB_DATABASE'); //从配置文件中获取数据库信息 $DB_USERNAME = getenv('DB_USERNAME'); $DB_PASSWORD = getenv('DB_PASSWORD'); set_time_limit(0); //设置超时时间为0,表示一直执行。当php在safe mode模式下无效,此时可能会导致导入超时,此时需要分段导入 $fp = @fopen($filename, "r") or die("不能打开SQL文件 $filename");//打开文件 //print_r($fp);exit; @$conf = mysqli_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD,$DB_DATABASE) or die("不能连接数据库 $DB_HOST");//连接数据库 // echo $filename; $_sql = file_get_contents($filename); $_arr = explode(';', $_sql); // dd($_arr);exit; foreach ($_arr as $_value) { mysqli_query($conf,"SET NAMES 'utf8'"); mysqli_query($conf,$_value.';'); } echo "<br>导入完成!"; }