作者 邓超

备份mysql

<?php
include_once "../vendor/autoload.php";
$dir = __DIR__."/mysql_back/";
if(!is_dir($dir)){
mkdir($dir,0775,true);
}
$tables = db()->query("show tables;")->fetchAll();
foreach ($tables as $table){
$table = array_values($table)[0];
$name = $dir.$table.".create.sql";
_echo("正在备份表结构 ".$table);
// 显示表结构
$c = db()->query("show create table {$table}")->fetch();
file_put_contents($name,$c['Create Table']);
if(in_array($table,['lists_auto','lists','bodies','bodies_back','lists_hot'])){
continue;
}
$datafile = $dir.$table.'.'.date('Ymd').".data.json";
$p = 0;
$limit = 1000;
while (1){
echo "当前备份 $p\r";
$lists = db()->all("select * from `{$table}` limit {$limit} offset ".($p*$limit));
if($lists){
foreach ($lists as $list)
file_put_contents($datafile,json_encode($list,true),FILE_APPEND);
}else{
break;
}
$p++;
}
echo "\n";
}
... ...