php不使用mysqlDump工具实现的mysql数据备份

  再无法使用mysqlDump等外部工具的时候,我们需要到处数据库备份的话,借助phpMyAdmin强大的功能就可以实现。如果我们想自己实现一个类似phpMysql的功能要如何去考虑了,因此,在这里我给大家分享一下我个人的思路。

  第一、观察phpmyadmin导出

    它导出一般是生成sql文件,咱们打开它的sql文件(找一个小的库),可以看到生成了两类型数据库语言:DDL(数据定义语言),DML(数据操纵语言)。通过这个细节,我们需要知道它是如何找到数据库里面的表,然后再找到各个表的生成语句的,最后找到它的insert语句是如何得到的。

    1、枚举数据库中的表:SHOW TABLES FROM schema

      使用这个语句能得到我们的结果

 

    2、展示表结构:show create table table_name

      使用这个语句能得到我们的结果

    3、生成insert语句:先查询表中的数据,再遍历拼接insert语句

 第二、借鉴他人的代码,写出自己的代码

    百度应该可以找到这样的代码,但自己要理解必须自己走几遍,自己在优化

   第三、 实际遇到的问题

    1、存在大数据表的时候

      当遇到数据库很大时,我们需要化解大小,将大的分割成小的。具体来说,就是以前可能是insert values 一张表所有的数据,现在应该是 每n条数据对应一个 insert values 。

      具体实现,参考下面提供的代码

          2、 数据表设置了外键的时候

      通过资料查找,可以再sql文件上加入:

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

     来跳过外键检查。

      从phpMyadmin的导出的sql文件看,它对有外键生成的表的结构语句应该是做了处理,最终它生成的语句是没有生成外键的语句的。它是在最后对这些做出的处理

    。

      这个地方还需要学习知识点,目前我感觉可能是使用了“SHOW INDEX FROM table_name” 语句去处理的,包括如果有触发器、存储过程也可能是使用show语句去拼接sql的

--
-- 限制导出的表
--

--
-- 限制表 `byt_admin_log`
--
ALTER TABLE `byt_admin_log`
  ADD CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `byt_admin_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- 限制表 `byt_carousel_item`
--
ALTER TABLE `byt_carousel_item`
  ADD CONSTRAINT `carousel` FOREIGN KEY (`carousel_id`) REFERENCES `byt_carousel` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

    3、使用事务

      在导出sql里面加入事务语句,从phpMyadmin里能找到它们(分别再开始和结尾),具体知识点请百度(我也要百度):

/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

 

/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

 

 

 第三、 附上弱弱的代码(提供两段代码,代码差异不大)

    1、代码1是先生成所有表的结构语句,在生成所有表的insert语句。

  1 <?php
  2 
  3 error_reporting(E_ALL);
  4 ini_set('display_errors', '1');
  5 
  6 class PdoMysql
  7 {
  8     private $_host;
  9     private $_user;
 10     private $_pwd;
 11     private $_dbname;
 12     private $_pdo;
 13     private static $connection = null;
 14 
 15     private function __construct()
 16     {
 17 
 18     }
 19 
 20     public static function getInstance()
 21     {
 22         if (!self::$connection instanceof static ) {
 23             self::$connection = new static();
 24         }
 25 
 26         return self::$connection;
 27     }
 28 
 29     public function setInfo($host, $user, $pwd, $dbname)
 30     {
 31         $this->_host   = $host;
 32         $this->_user   = $user;
 33         $this->_pwd    = $pwd;
 34         $this->_dbname = $dbname;
 35         $this->connect();
 36     }
 37 
 38     public function connect()
 39     {
 40         try {
 41             $_pdo = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_user, $this->_pwd);
 42             $_pdo->exec("SET NAMES utf8");
 43         } catch (PDOException $e) {
 44             die("Connection fail:" . $e->getMessage());
 45         }
 46 
 47         // 把$_pdo这个句柄放在静态属性,方便以下方法调用
 48         self::$connection = $_pdo;
 49     }
 50 
 51     public function __get($name)
 52     {
 53         $method = 'get' . ucfirst($name);
 54         if (method_exists($this, $method)) {
 55             return call_user_func([$this, $method], func_get_args());
 56         }
 57 
 58         return null;
 59     }
 60 
 61     public function getConnection()
 62     {
 63         return self::$connection;
 64     }
 65 
 66     public function _select($table, $fields = '*', $where = null, $result_type = PDO::FETCH_ASSOC)
 67     {
 68         if ($fields == '*' and $where == null) {
 69             $sql  = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
 70             $stmt = self::$connection->prepare($sql);
 71             $stmt->execute();
 72             while ($row = $stmt->fetch($result_type)) {
 73                 $rows[] = $row;
 74             }
 75             return $rows;
 76         }
 77         if ($where != null) {
 78             if (!is_array($where)) {
 79                 return false;
 80             }
 81 
 82             // 赋值给定义的属性交给以下foreacharray处理,返回的是一个字符串
 83             $this->_array = $where;
 84             $where        = $this->foreacharray();
 85             if ($where) {
 86                 $sql  = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
 87                 $stmt = self::$connection->prepare($sql);
 88                 $stmt->execute();
 89                 while ($row = $stmt->fetch($result_type)) {
 90                     $rows[] = $row;
 91                 }
 92             }
 93             return $rows;
 94         }
 95     }
 96 
 97     public function exec($sql)
 98     {
 99         empty($sql) && die("SQL is require!");
100 
101         return $this->connection->exec($sql);
102     }
103 
104     public function queryOneAtSql($sql, $resultType = PDO::FETCH_ASSOC)
105     {
106         empty($sql) && die("SQL is require!");
107         $stmt = $this->connection->prepare($sql);
108         $stmt->execute();
109         return $stmt->fetch($resultType);
110 
111     }
112 
113     public function queryRowsAtSql($sql, $resultType = PDO::FETCH_ASSOC)
114     {
115         empty($sql) && die("SQL is require!");
116         $rows = [];
117         $stmt = $this->connection->prepare($sql);
118         $stmt->execute();
119         while ($row = $stmt->fetch($resultType)) {
120             $rows[] = $row;
121         }
122 
123         return $rows;
124     }
125 
126     protected function foreachstr()
127     {
128         if (!is_array($this->_array)) {
129             return false;
130         }
131 
132         $fields = '';
133         $values = '';
134         foreach ($this->_array as $key => $val) {
135             $fields .= $key . ',';
136             $values .= $val . ',';
137         }
138         $this->_fields = rtrim($fields, ',');
139         $this->_values = str_replace(',', '\',\'', rtrim($values, ','));
140     }
141 
142     protected function foreacharray()
143     {
144         if (!is_array($this->_array)) {
145             return false;
146         }
147 
148         $str = '';
149         foreach ($this->_array as $key => $val) {
150             if ($key == $val) {
151                 return false;
152             }
153             // 防止sql注入
154             $str .= $key . ' = ' . "'$val'" . ' and ';
155         }
156         return substr($str, 0, strrpos($str, 'and'));
157     }
158 
159     public function count($table, $where = null)
160     {
161         $sql = '';
162         if (is_null($where)) {
163             $sql .= "select count(*) from {$table}";
164         } else {
165             $this->_array = $where;
166             $where        = $this->foreacharray();
167             $sql .= "select count(*) from {$table} " . ($where == null ? null : "where " . $where);
168         }
169 
170         $rowCount = $this->queryOneAtSql($sql, PDO::FETCH_NUM);
171         return $rowCount[0];
172     }
173 }
174 
175 class DumpData
176 {
177     public $saveFileName = '';
178 
179     public $dbInfo = [];
180 
181     private $db = null;
182 
183     private $fp = null;
184 
185     public $maxCount = 100;
186 
187     public $maxInsertNum = 50;
188 
189     public function __construct($dbInfo, $saveFileName = '')
190     {
191         $this->dbInfo       = $dbInfo;
192         $this->saveFileName = $saveFileName;
193         $this->db           = PdoMysql::getInstance();
194         $this->db->setInfo($this->dbInfo['host'], $this->dbInfo['user'], $this->dbInfo['pwd'], $this->dbInfo['dbname']);
195         $this->db->exec('set names utf8');
196     }
197 
198     public function backupAll($table = null)
199     {
200         set_time_limit(0);
201         echo '数据备份中,请稍候......', PHP_EOL;
202         $isDropInfo     = '';
203         $insertSQL      = '';
204         $tables         = [];
205         $pathName       = __DIR__ . DIRECTORY_SEPARATOR . 'dumpData';
206         createDictory($pathName);
207         $fileName = $pathName . DIRECTORY_SEPARATOR . ($this->saveFileName ? $this->saveFileName : 'MySQL_data_backup_' . $this->dbInfo['dbname'] . '_' ) . date('YmdHis') . '.sql';
208         $this->fp = fopen($fileName, 'a+');
209         // 枚举该数据库所有的表
210         $sql = "SHOW TABLES FROM {$this->dbInfo['dbname']}";
211         if ($table) {
212             $sql = sprintf("%s %s", $sql, " LIKE '{$table}'");
213         }
214         echo 'sql:', $sql, PHP_EOL;
215         $tables = $this->db->queryRowsAtSql($sql, PDO::FETCH_NUM);217         try {
218             $str = 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . PHP_EOL .
219                 'SET time_zone = "+00:00";' . PHP_EOL .
220                 PHP_EOL .
221                 '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . PHP_EOL .
222                 '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . PHP_EOL .
223                 '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;'. PHP_EOL .
224                 '/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;'. PHP_EOL .
225                 '/*!40101 SET NAMES utf8 */;'. PHP_EOL;
226             fwrite($this->fp, $str);            
227             foreach ($tables as $key => $val) {
228                 if (!$this->backupOneTable($val[0])) {
229                     continue;
230                 }
231                 usleep(1000);
232             }
233             fclose($this->fp);235             echo '数据备份成功!', '文件存放在:', $fileName, PHP_EOL;
236 
237         } catch (Exception $e) {
238             @unlink($fileName);
239             var_dump($e);
240             echo '数据备份失败!';242         }
243     }
244 
245     public function backupOneTable($table)
246     {
247         $sql = "show create table {$table}";
248         echo $sql, PHP_EOL;
249         $row            = $this->db->queryOneAtSql($sql, PDO::FETCH_NUM);
250         $isDropInfo     = "DROP TABLE IF EXISTS `" . $table . "`;\r\n";
251         $tableStructure = $isDropInfo . $row[1] . ";\r\n\r\n";
252         fwrite($this->fp, $tableStructure);
253         $count = $this->db->count($table);
254         if (!$count) {
255             return false;
256         }
257 
258         echo $count, PHP_EOL;
259         if ($count > $this->maxCount) {
260             $total = ceil($count / $this->maxCount);
261             for ($i = 1; $i <= $total; $i++) {
262                 $limit = ($i - 1) * $this->maxCount;
263                 $sql   = "select * from {$table} WHERE 1 LIMIT {$limit}, {$this->maxCount};";
264                 echo $sql, PHP_EOL;
265                 $this->backupTableData($table, $sql);
266             }
267         } else {
268             $this->backupTableData($table, "SELECT * FROM " . $table);
269         }
270 
271         return true;
272     }
273 
274     public function backupTableData($table, $sql)
275     {
276         $res    = $this->db->queryRowsAtSql($sql);
277         $sqlStr = "";
278         $num = 1;
279         $sr = '';
280         foreach ($res as $key => $value) {
281             $sr .= '( ';
282             foreach ($value as $key => $v) {
283                 $sr .= "'" . $v . "',";//htmlspecialchars($v, ENT_QUOTES)
284             }
285             $sr = substr($sr, 0, strlen($sr) - 1);
286             $sr .= '),';
287             if (($num++ % $this->maxInsertNum) == 0) {
288                 $sr = substr($sr, 0, strlen($sr) - 1);
289                 $sqlStr .= "INSERT INTO `" . $table . "` VALUES " . $sr  . ';' . PHP_EOL;
290                 // echo 'InsSql:', $sqlStr, PHP_EOL;
291                 $sr = '';
292             }
293 
294         }
295 
296         unset($res);
297         $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1);
298         echo $sqlStr, PHP_EOL, '__________________________________________', PHP_EOL;
299         fwrite($this->fp, $sqlStr);
300         fwrite($this->fp, "\r\n");
301     }
302 }
303 
304 function createDictory($path, $loop = false, $mode = 0777)
305 {
306     if (!is_dir($path)) {
307         mkdir($path, $mode, $loop);
308     }
309 }
310 
311 
312 $dump = new DumpData([
313     'host'   => 'localhost',
314     'user'   => 'root',
315     'pwd'    => 'root',
316     'dbname' => 'jcycms',
317 ]);
318 
319 
320 $dump->backupAll();
321 
322 
323 // SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
324 // SET time_zone = "+00:00";
325 
326 
327 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
328 /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
329 /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
330 /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
331 /*!40101 SET NAMES utf8 */;
332 
333 /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
334 /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
335 /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

 

    2、代码2是先生成一个表的结构语句、生成一个表的insert语句,在生成下一个。

 

 

  1 <?php
  2 
  3 error_reporting(E_ALL);
  4 ini_set('display_errors', '1');
  5 
  6 class PdoMysql
  7 {
  8     private $_host;
  9     private $_user;
 10     private $_pwd;
 11     private $_dbname;
 12     private $_pdo;
 13     private static $connection = null;
 14 
 15     private function __construct()
 16     {
 17 
 18     }
 19 
 20     public static function getInstance()
 21     {
 22         if (!self::$connection instanceof static ) {
 23             self::$connection = new static();
 24         }
 25 
 26         return self::$connection;
 27     }
 28 
 29     public function setInfo($host, $user, $pwd, $dbname)
 30     {
 31         $this->_host   = $host;
 32         $this->_user   = $user;
 33         $this->_pwd    = $pwd;
 34         $this->_dbname = $dbname;
 35         $this->connect();
 36     }
 37 
 38     public function connect()
 39     {
 40         try {
 41             $_pdo = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_user, $this->_pwd);
 42             $_pdo->exec("SET NAMES utf8");
 43         } catch (PDOException $e) {
 44             die("Connection fail:" . $e->getMessage());
 45         }
 46 
 47         // 把$_pdo这个句柄放在静态属性,方便以下方法调用
 48         self::$connection = $_pdo;
 49     }
 50 
 51     public function __get($name)
 52     {
 53         $method = 'get' . ucfirst($name);
 54         if (method_exists($this, $method)) {
 55             return call_user_func([$this, $method], func_get_args());
 56         }
 57 
 58         return null;
 59     }
 60 
 61     public function getConnection()
 62     {
 63         return self::$connection;
 64     }
 65 
 66     public function _select($table, $fields = '*', $where = null, $result_type = PDO::FETCH_ASSOC)
 67     {
 68         if ($fields == '*' and $where == null) {
 69             $sql  = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
 70             $stmt = self::$connection->prepare($sql);
 71             $stmt->execute();
 72             while ($row = $stmt->fetch($result_type)) {
 73                 $rows[] = $row;
 74             }
 75             return $rows;
 76         }
 77         if ($where != null) {
 78             if (!is_array($where)) {
 79                 return false;
 80             }
 81 
 82             // 赋值给定义的属性交给以下foreacharray处理,返回的是一个字符串
 83             $this->_array = $where;
 84             $where        = $this->foreacharray();
 85             if ($where) {
 86                 $sql  = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
 87                 $stmt = self::$connection->prepare($sql);
 88                 $stmt->execute();
 89                 while ($row = $stmt->fetch($result_type)) {
 90                     $rows[] = $row;
 91                 }
 92             }
 93             return $rows;
 94         }
 95     }
 96 
 97     public function exec($sql)
 98     {
 99         empty($sql) && die("SQL is require!");
100 
101         return $this->connection->exec($sql);
102     }
103 
104     public function queryOneAtSql($sql, $resultType = PDO::FETCH_ASSOC)
105     {
106         empty($sql) && die("SQL is require!");
107         $stmt = $this->connection->prepare($sql);
108         $stmt->execute();
109         return $stmt->fetch($resultType);
110 
111     }
112 
113     public function queryRowsAtSql($sql, $resultType = PDO::FETCH_ASSOC)
114     {
115         empty($sql) && die("SQL is require!");
116         $rows = [];
117         $stmt = $this->connection->prepare($sql);
118         $stmt->execute();
119         while ($row = $stmt->fetch($resultType)) {
120             $rows[] = $row;
121         }
122 
123         return $rows;
124     }
125 
126     protected function foreachstr()
127     {
128         if (!is_array($this->_array)) {
129             return false;
130         }
131 
132         $fields = '';
133         $values = '';
134         foreach ($this->_array as $key => $val) {
135             $fields .= $key . ',';
136             $values .= $val . ',';
137         }
138         $this->_fields = rtrim($fields, ',');
139         $this->_values = str_replace(',', '\',\'', rtrim($values, ','));
140     }
141 
142     protected function foreacharray()
143     {
144         if (!is_array($this->_array)) {
145             return false;
146         }
147 
148         $str = '';
149         foreach ($this->_array as $key => $val) {
150             if ($key == $val) {
151                 return false;
152             }
153             // 防止sql注入
154             $str .= $key . ' = ' . "'$val'" . ' and ';
155         }
156         return substr($str, 0, strrpos($str, 'and'));
157     }
158 
159     public function count($table, $where = null)
160     {
161         $sql = '';
162         if (is_null($where)) {
163             $sql .= "select count(*) from {$table}";
164         } else {
165             $this->_array = $where;
166             $where        = $this->foreacharray();
167             $sql .= "select count(*) from {$table} " . ($where == null ? null : "where " . $where);
168         }
169 
170         $rowCount = $this->queryOneAtSql($sql, PDO::FETCH_NUM);
171         return $rowCount[0];
172     }
173 }
174 
175 class DumpData
176 {
177     public $saveFileName = '';
178 
179     public $dbInfo = [];
180 
181     private $db = null;
182 
183     private $fp = null;
184 
185     public $maxCount = 100;
186 
187     public $maxInsertNum = 50;
188 
189     public function __construct($dbInfo, $saveFileName = '')
190     {
191         $this->dbInfo       = $dbInfo;
192         $this->saveFileName = $saveFileName;
193         $this->db           = PdoMysql::getInstance();
194         $this->db->setInfo($this->dbInfo['host'], $this->dbInfo['user'], $this->dbInfo['pwd'], $this->dbInfo['dbname']);
195         $this->db->exec('set names utf8');
196     }
197 
198     public function backupAll($table = null)
199     {
200         set_time_limit(0);
201         echo '数据备份中,请稍候......', PHP_EOL;
202         $isDropInfo     = '';
203         $insertSQL      = '';
204         $tables         = [];
205         $pathName       = __DIR__ . DIRECTORY_SEPARATOR . 'dumpData';
206         createDictory($pathName);
207         $fileName = $pathName . DIRECTORY_SEPARATOR . ($this->saveFileName ? $this->saveFileName : 'MySQL_data_backup_' . $this->dbInfo['dbname'] . '_' ) . date('YmdHis') . '.sql';
208         $this->fp = fopen($fileName, 'a+');
209         // 枚举该数据库所有的表
210         $sql = "SHOW TABLES FROM {$this->dbInfo['dbname']}";
211         if ($table) {
212             $sql = sprintf("%s %s", $sql, " LIKE '{$table}'");
213         }
214         echo 'sql:', $sql, PHP_EOL;
215         $tables = $this->db->queryRowsAtSql($sql, PDO::FETCH_NUM);217         $tableList = [];
218         try {
219             $str = 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . PHP_EOL .
220                 'SET time_zone = "+00:00";' . PHP_EOL .
221                 PHP_EOL .
222                 '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . PHP_EOL .
223                 '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . PHP_EOL .
224                 '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;'. PHP_EOL .
225                 '/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;'. PHP_EOL .
226                 '/*!40101 SET NAMES utf8 */;'. PHP_EOL;
227             fwrite($this->fp, $str);
228             foreach ($tables as $key => $val) {
229                 $this->addTable($val[0]);
230                 $tableList[] = $val[0];
231             }
232             $tables = null;
233             foreach ($tableList as $key => $table) {
234                 if (!$this->addRows($table)) {
235                     continue;
236                 }
237             }
238             fclose($this->fp);240             echo '数据备份成功!', '文件存放在:', $fileName, PHP_EOL;
241 
242         } catch (Exception $e) {
243             @unlink($fileName);
244             var_dump($e);
245             echo '数据备份失败!';247         }
248     }
249 
250     private function addTable($table) 
251     {
252         $sql = "show create table {$table}";
253         echo $sql, PHP_EOL;
254         $row            = $this->db->queryOneAtSql($sql, PDO::FETCH_NUM);
255         $isDropInfo     = "DROP TABLE IF EXISTS `" . $table . "`;\r\n";
256         $tableStructure = $isDropInfo . $row[1] . ";\r\n\r\n";
257         fwrite($this->fp, $tableStructure);
258     }
259 
260     private function addRows($table)
261     {
262 
263         $count = $this->db->count($table);
264         if (!$count) {
265             return false;
266         }
267 
268         echo 'Data Count: ', $count, PHP_EOL;
269         if ($count > $this->maxCount) {
270             $total = ceil($count / $this->maxCount);
271             for ($i = 1; $i <= $total; $i++) {
272                 $limit = ($i - 1) * $this->maxCount;
273                 $sql   = "select * from {$table} WHERE 1 LIMIT {$limit}, {$this->maxCount};";
274                 echo $sql, PHP_EOL;
275                 $this->backupTableData($table, $sql);
276             }
277         } else {
278             $this->backupTableData($table, "SELECT * FROM " . $table);
279         }
280 
281         return true;
282     }
283 
284     public function backupTableData($table, $sql)
285     {
286         $res    = $this->db->queryRowsAtSql($sql);
287         $sqlStr = "";
288         $num = 1;
289         $sr = '';
290         foreach ($res as $key => $value) {
291             $sr .= '( ';
292             foreach ($value as $key => $v) {
293                 $sr .= "'" . $v . "',";//htmlspecialchars($v, ENT_QUOTES)
294             }
295             $sr = substr($sr, 0, strlen($sr) - 1);
296             $sr .= '),';
297             if (($num++ % $this->maxInsertNum) == 0) {
298                 $sr = substr($sr, 0, strlen($sr) - 1);
299                 $sqlStr .= "INSERT INTO `" . $table . "` VALUES " . $sr  . ';' . PHP_EOL;
300                 // echo 'InsSql:', $sqlStr, PHP_EOL;
301                 $sr = '';
302             }
303 
304         }
305 
306         unset($res);
307         $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1);
308         echo $sqlStr, PHP_EOL, '__________________________________________', PHP_EOL;
309         fwrite($this->fp, $sqlStr);
310         fwrite($this->fp, "\r\n");
311     }
312 }
313 
314 function createDictory($path, $loop = false, $mode = 0777)
315 {
316     if (!is_dir($path)) {
317         mkdir($path, $mode, $loop);
318     }
319 }
320 
321 
322 $dump = new DumpData([
323     'host'   => 'localhost',
324     'user'   => 'root',
325     'pwd'    => 'root',
326     'dbname' => 'yii2_jcycms',
327 ]);
328 
329 
330 $dump->backupAll();

 

posted @ 2020-03-09 23:32  yangboom  阅读(418)  评论(0编辑  收藏  举报
TOP