作者 邓超

备份mysql

  1 +<?php
  2 +
  3 +
  4 +include_once "../vendor/autoload.php";
  5 +
  6 +$dir = __DIR__."/mysql_back/";
  7 +if(!is_dir($dir)){
  8 + mkdir($dir,0775,true);
  9 +}
  10 +
  11 +$tables = db()->query("show tables;")->fetchAll();
  12 +
  13 +
  14 +foreach ($tables as $table){
  15 + $table = array_values($table)[0];
  16 +
  17 + $name = $dir.$table.".create.sql";
  18 + _echo("正在备份表结构 ".$table);
  19 + // 显示表结构
  20 + $c = db()->query("show create table {$table}")->fetch();
  21 +
  22 + file_put_contents($name,$c['Create Table']);
  23 +
  24 + if(in_array($table,['lists_auto','lists','bodies','bodies_back','lists_hot'])){
  25 + continue;
  26 + }
  27 +
  28 + $datafile = $dir.$table.'.'.date('Ymd').".data.json";
  29 + $p = 0;
  30 + $limit = 1000;
  31 + while (1){
  32 + echo "当前备份 $p\r";
  33 + $lists = db()->all("select * from `{$table}` limit {$limit} offset ".($p*$limit));
  34 + if($lists){
  35 + foreach ($lists as $list)
  36 + file_put_contents($datafile,json_encode($list,true),FILE_APPEND);
  37 + }else{
  38 + break;
  39 + }
  40 + $p++;
  41 +
  42 + }
  43 +
  44 + echo "\n";
  45 +
  46 +}
  47 +
  48 +