php实例分享之mysql数据备份

本代码实现了表结构和数据完全分开,默认有一个文件会记录所有表的结构,然后表中数据的备份 如果超过分卷的大小则会分成多个文件,不然则一个文件。

备份:表结构和数据完全分开,默认有一个文件会记录所有表的结构,然后表中数据的备份 如果超过分卷的大小则会分成多个文件,不然则一个文件,参考了别人的代码,不过写的嘛,差强 人意,以后慢慢改吧。。。

代码如下:

  1. <?php
  2. /*
  3. * Created on 2014
  4. * Link for 527891885@qq.com
  5. * This is seocheck backup class
  6. */
  7. class DbBackUp {
  8. private $conn;
  9. private $dbName;
  10. private $host;
  11. private $tag = '_b';
  12. //构造方法 链接数据库
  13. public function __construct($host='localhost', $dbUser='root', $dbPwd='', $dbName="seocheck", $charset='utf8') {
  14. @ob_start();
  15. @set_time_limit(0);
  16. $this->conn = mysql_connect($host, $dbUser, $dbPwd, true);
  17. if(!$this->conn) die("数据库系统连接失败!");
  18. mysql_query("set names ".$charset, $this->conn);
  19. mysql_select_db($dbName, $this->conn) or die("数据库连接失败!");
  20. $this->host = $host;
  21. $this->dbName = $dbName;
  22. }
  23. //获取数据库所有表名
  24. public function getTableNames () {
  25. $tables = array();
  26. $result = mysql_list_tables($this->dbName, $this->conn);
  27. if(!$result) die('MySQL Error: ' . mysql_error());
  28. while($row = mysql_fetch_row($result)) {
  29. $tables[] = $row[0];
  30. }
  31. return $tables;
  32. }
  33. //获取数据库表的字段信息
  34. public function getFieldsByTable ($table) {
  35. $fields = array();
  36. $str = '';
  37. $res = mysql_query("SHOW CREATE TABLE `{$table}`", $this->conn);
  38. if(!$res) die('MySQL Error: ' . mysql_error());
  39. while($rows = mysql_fetch_assoc($res)) {
  40. $str = str_replace("CREATE TABLE `{$table}` (", "", $rows['Create Table']);//DROP TABLE IF EXISTS `{$table}`\n
  41. $str = "--\n-- Table structure for table `{$table}`\n--\n\nCREATE TABLE IF NOT EXISTS `{$table}` ( ".$str;
  42. $str = str_replace(",", ", ", $str);
  43. $str = str_replace("`) ) ENGINE=InnoDB ", "`)\n ) ENGINE=InnoDB ", $str);
  44. $str .=";\n\n";
  45. //$str = $str.";\n\n--\n-- Dumping data for table `{$table}`\n--\n\n";
  46. $fields[$rows['Table']] = $str;
  47. }
  48. return $fields;
  49. }
  50. //获取表中的数据
  51. public function getDataByTable($table) {
  52. $data = array();
  53. $str = '';
  54. $res = mysql_query("SELECT * FROM `{$table}`", $this->conn);
  55. if(!$res) die('MySQL Error: ' . mysql_error());
  56. while($rows = mysql_fetch_assoc($res)) {
  57. if(!emptyempty($rows)) {
  58. $data[] = $rows;
  59. }
  60. }
  61. $keys = array_keys($data[0]);
  62. foreach ($keys as $k=>$v) {
  63. $keys[$k] = '`'.$v.'`';
  64. }
  65. $key = join(', ', $keys);
  66. $str = "INSERT INTO `{$table}` ({$key}) VALUES\n";
  67. foreach ($data as $k=>$v) {
  68. $str.="(";
  69. while (list($key, $val) = each($v)) {
  70. if(!is_numeric($val)) {
  71. $str.= "'".$val."', ";
  72. } else {
  73. $str.= $val.', ';
  74. }
  75. }
  76. $str = substr($str, 0, -2);// 后边有空格 所以从-2 开始截取
  77. if($k+1 == count($data)) {
  78. $str.=");\n\n-- --------------------------------------------------------\n\n";
  79. } else {
  80. $str.="),\n";
  81. }
  82. }
  83. return $str;
  84. }
  85. //备份数据库
  86. public function getBackUpDataByTable ($tables, $path='', $fileName = 'seocheck', $subsection = '2') {
  87. if(emptyempty($tables)) $this->_showMsg('未能指定要备份的表!!!', true);
  88. $page = 0;//卷数
  89. $path = emptyempty($path) ? $_SERVER['DOCUMENT_ROOT'].'/core/Runtime/Data/'.$fileName.'Demo/' : $path;
  90. if(!file_exists($path)) {
  91. mkdir($path, 0777, true);
  92. }
  93. $mysql_info = $this->_retrieve();
  94. $fieldsByTable = array();
  95. if(is_array($tables)) {
  96. $this->_showMsg('开始备份,数据正在初始化中,请勿关闭浏览器...');
  97. $fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $mysql_info, $method="ab+");
  98. if($fw !== false) {
  99. $this->_showMsg('备份数据库基本信息成功。。。');
  100. }
  101. foreach ($tables as $table) {
  102. $tableInfo = $this->getFieldsByTable($table);
  103. if(!emptyempty($tableInfo)) {
  104. $this->_showMsg('获取表['.$table.']结构成功。。。');
  105. $fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $tableInfo[$table], $method="ab+");
  106. if($fw === false) {
  107. $this->_showMsg('备份表['.$table.']结构失败。。。', true);
  108. } else {
  109. $this->_showMsg('备份表['.$table.']结构成功,开始获取数据。。。');
  110. };
  111. } else {
  112. $this->_showMsg('获取数据库['.$this->dbName.']表结构失败,请稍后再试!。。。', true);
  113. }
  114. $this->_insertSqlByTableForAll($path, $table, $subsection);
  115. }
  116. } else {
  117. $this->_showMsg('开始备份,数据正在初始化中,请勿关闭浏览器...');
  118. $tableInfo = $this->getFieldsByTable($tables);
  119. if(!emptyempty($tableInfo)) {
  120. $this->_showMsg('获取表['.$tables.']结构成功。。。');
  121. $fw = $this->writeFileByBackUpData($path.$this->dbName.'_'.$tables.'_table.sql', $mysql_info.$tableInfo[$tables]);
  122. if($fw === false) {
  123. $this->_showMsg('备份表['.$tables.']结构失败。。。', true);
  124. } else {
  125. $this->_showMsg('备份表['.$tables.']结构成功,开始获取数据。。。');
  126. }
  127. } else {
  128. $this->_showMsg('获取表['.$tables.']结构失败,请稍后再试!。。。', true);
  129. }
  130. $res = $this->_insertSqlByTableForAll($path, $tables, $subsection);
  131. }
  132. }
  133. //数据库基本信息
  134. private function _retrieve() {
  135. $backUp = '';
  136. $backUp .= '--' . "\n";
  137. $backUp .= '-- MySQL database dump' . "\n";
  138. $backUp .= '-- Created by DbBackUp class, Power By chujiu. ' . "\n";
  139. $backUp .= '--' . "\n";
  140. $backUp .= '-- 主机: ' . $this->host . "\n";
  141. $backUp .= '-- 生成日期: ' . date ( 'Y' ) . ' 年 ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . "\n";
  142. $backUp .= '-- MySQL版本: ' . mysql_get_server_info () . "\n";
  143. $backUp .= '-- PHP 版本: ' . phpversion () . "\n";
  144. $backUp .= "\n\n";
  145. $backUp .= "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';\n";
  146. $backUp .= "SET time_zone = '+00:00';\n\n";
  147. $backUp .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n";
  148. $backUp .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n";
  149. $backUp .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n";
  150. $backUp .= "/*!40101 SET NAMES utf8*/;\n\n";
  151. $backUp .= "--\n-- Database: `{$this->dbName}`\n--\n\n-- --------------------------------------------------------\n\n";
  152. return $backUp;
  153. }
  154. /**
  155. * 插入单条记录
  156. *
  157. * @param string $row
  158. */
  159. private function _insertSql($row, $table) {
  160. // sql字段逗号分割
  161. $insert = '';
  162. $insert .= "INSERT INTO `" . $table . "` VALUES(";
  163. foreach($row as $key=>$val) {
  164. $insert .= "'".$val."',";
  165. }
  166. $insert = substr($insert, 0 ,-1);
  167. $insert .= ");" . "\n";
  168. return $insert;
  169. }
  170. /**
  171. * 生成一个表的inser语句
  172. * @param string $table
  173. * @param string $subsection 分卷大小
  174. */
  175. private function _insertSqlByTableForAll($path, $table, $subsection) {
  176. $i = 0;
  177. $insertSqlByTable = '';
  178. $res = mysql_query("SELECT * FROM `{$table}`", $this->conn);
  179. if(!$res) die('MySQL Error: ' . mysql_error());
  180. while($rows = mysql_fetch_assoc($res)) {
  181. $insertSqlByTable .= $this->_insertSql($rows, $table);
  182. $size = strlen($insertSqlByTable);
  183. if($size > $subsection*1024*1024) {
  184. $fw = $this->writeFileByBackUpData($path.$table.$i.$this->tag.'.sql', $insertSqlByTable);
  185. if($fw === false) $this->_showMsg('数据库表['.$table.'],卷 '.$i.' 写入文件失败,请稍后再试!!!',true);
  186. $this->_showMsg('数据库表['.$table.'],卷 '.$i.' 备份成功!备份文件:[ '.$path.$table.$i.$this->tag.'.sql ]');
  187. $insertSqlByTable = '';
  188. $i+=1;
  189. }
  190. }
  191. // insertSqlByTable大小不够分卷大小
  192. if ($insertSqlByTable != "") {
  193. $fw = $this->writeFileByBackUpData($path.$table.$this->tag.'.sql', $insertSqlByTable);
  194. if($fw === false) $this->_showMsg('数据库表['.$table.']写入文件失败,请稍后再试!!!备份文件:[ '.$path.$table.$this->tag.'.sql ]',true);
  195. $this->_showMsg('数据库表['.$table.'] 备份成功!备份文件:[ '.$path.$table.$this->tag.'.sql ]');
  196. }
  197. $this->_showMsg('数据库表['.$table.']全部备份成功!');
  198. }
  199. // 写入文件
  200. public function writeFileByBackUpData($fileName, $data, $method="rb+", $iflock=1, $check=1, $chmod=1){
  201. $check && @strpos($fileName, '..')!==false && exit('Forbidden');
  202. @touch($fileName);
  203. $handle = @fopen($fileName, $method);
  204. if($iflock) {
  205. @flock($handle,LOCK_EX);
  206. }
  207. $fw = @fwrite($handle,$data);
  208. if($method == "rb+") ftruncate($handle, strlen($data));
  209. fclose($handle);
  210. $chmod && @chmod($fileName,0777);
  211. return $fw;
  212. }
  213. /**
  214. * path: 生成压缩包的路径
  215. * fileName : 要压缩的文件名 通常和path 同一目录
  216. */
  217. public function createZipByBackUpFile($path) {
  218. $db_base_files = $this->getFileByBackUpDir($path);
  219. if(!emptyempty($db_base_files)) {
  220. $zip = new ZipArchive;
  221. if($zip->open($path.$this->dbName.date('Ymd').'.zip', ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
  222. die ("cannot open".$this->dbName.date('Ymd')."zip for writing.");
  223. foreach ($db_base_files as $key => $value) {
  224. if(is_file($value)) {
  225. $file_name = basename($value);
  226. $info[] = $zip->addFile($value, $file_name);// 避免压缩包里有文件的路径
  227. }
  228. }
  229. $zip->close();
  230. if(file_exists($path.$this->dbName.date('Ymd').'.zip'))
  231. foreach ($db_base_files as $val) {
  232. unlink($val);
  233. }
  234. if(count(array_filter($info)) > 0) return true;
  235. }
  236. return false;
  237. }
  238. //获取文件
  239. public function getFileByBackUpDir($path) {
  240. $info = array();
  241. $db_base_files = array();
  242. if( @file_exists($path) && is_dir($path) ) {
  243. if ($dh = opendir($path)) {
  244. while (($file = readdir($dh)) !== false) {
  245. if($file != '.' && $file != '..') {
  246. if( strripos($file, 'seocheck') !== false ) {
  247. $db_base_files[] = $path.$file;
  248. }
  249. }
  250. }
  251. closedir($dh);
  252. }
  253. }
  254. return $db_base_files;
  255. }
  256. /**
  257. * @path: 生成压缩包的路径
  258. * @fileName : 要解压的文件名 默认解压到path 目录
  259. */
  260. public function uncompressZip($path, $zipName) {
  261. $path = emptyempty($path) ? $_SERVER['DOCUMENT_ROOT'].'/core/Runtime/Data/' : $path;
  262. $zip = new ZipArchive;
  263. if ($zip->open($path.$zipName) === TRUE) {
  264. $zip->extractTo($path);
  265. $zip->close();
  266. return true;
  267. } else {
  268. return false;
  269. }
  270. }
  271. //导入数据库
  272. public function importingDataBySqlFile () {
  273. }
  274. // 及时输出信息
  275. private function _showMsg($msg,$err=false){
  276. if($err === true) {
  277. echo "<p ><span >ERROR: --- " . $msg . "</span></p>";exit;
  278. }
  279. echo "<p ><span >OK: --- " . $msg . "</span></p>";
  280. }
  281. // 锁定数据库,以免备份或导入时出错
  282. private function lock($table, $op = "WRITE") {
  283. if (mysql_query ( "lock tables " . $table . " " . $op ))
  284. return true;
  285. else
  286. return false;
  287. }
  288. // 解锁
  289. private function unlock() {
  290. if (mysql_query ( "unlock tables" ))
  291. return true;
  292. else
  293. return false;
  294. }
  295. // 析构
  296. public function __destruct() {
  297. if($this->conn){
  298. mysql_query ( "unlock tables", $this->conn );
  299. mysql_close ( $this->conn );
  300. }
  301. }
  302. }
  303. ?>