0

0

MySQL的备份

php中文网

php中文网

发布时间:2016-07-25 08:50:37

|

827人浏览过

|

来源于php中文网

原创

本来想着用SHOW CREATE TABLE + ergodic 来做备份的但是发现如果Table 有 comment 而且还是乱码的话,会导致SHOW CREATE TABLE 出来的脚本缺少一个符号。所以有了这个版本。
  1. class MysqlExport{
  2. /**
  3. * database connect
  4. */
  5. private $_db;
  6. private $_resource;
  7. /**
  8. * create table structure sql
  9. */
  10. private $_create_table = '';
  11. public function __construct($host = '', $user = '', $pass = '', $db = '', $port = 3306) {
  12. if (empty($host) || empty($user)) {
  13. } else {
  14. $this->real_connect($host, $user, $pass, $db, $port);
  15. }
  16. }
  17. public function init() {
  18. return $this;
  19. }
  20. /**
  21. * 连接数据库
  22. */
  23. public function real_connect($host, $user, $pass, $db = '', $port = 3306) {
  24. $this->_db = mysql_connect($host . ':' . $port, $user, $pass);
  25. if ($db) {
  26. $this->select_db($db);
  27. }
  28. return $this->init();
  29. }
  30. /**
  31. * 选择数据库
  32. */
  33. public function select_db($db) {
  34. if (mysql_select_db($db, $this->_db)) {
  35. return true;
  36. }
  37. }
  38. /**
  39. * 查询语句
  40. */
  41. public function query($sql) {
  42. if ($this->_db) {
  43. if ($this->_resource = mysql_query($sql, $this->_db)) {
  44. return $this->init();
  45. }
  46. }
  47. throw new Exception($this->get_error());
  48. }
  49. /**
  50. * 获取结果集
  51. */
  52. public function fetch_array($arg = MYSQL_BOTH) {
  53. $result = array();
  54. if ($this->_resource && !mysql_errno($this->_db)) {
  55. while ($rs = mysql_fetch_array($this->_resource, $arg)) {
  56. $result[] = $rs;
  57. }
  58. }
  59. return $result;
  60. }
  61. /**
  62. * 获取错误
  63. */
  64. public function get_error() {
  65. return mysql_errno($this->_db) . ": " . mysql_error($this->_db). "\n";
  66. }
  67. /**
  68. * 显示数据表
  69. */
  70. public function show_tables($table = '') {
  71. $sql = "SHOW TABLES";
  72. $sql .= $table ? " LIKE '{$table}'" : '';
  73. $result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  74. return $result;
  75. }
  76. /**
  77. * 显示数据表字段
  78. */
  79. public function show_columns($table) {
  80. if (empty($table)) {
  81. return array();
  82. }
  83. $sql = "SHOW FULL COLUMNS FROM {$table}";
  84. $result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  85. return $result;
  86. }
  87. /**
  88. * 显示数据表状态
  89. */
  90. public function show_table_status($table) {
  91. if (empty($table)) {
  92. return array();
  93. }
  94. $result = $this->query("SHOW TABLE STATUS LIKE '{$table}'")->fetch_array(MYSQL_ASSOC);
  95. $result = reset($result);
  96. return $result;
  97. }
  98. /**
  99. * 显示数据表结构
  100. */
  101. public function show_create_table($table) {
  102. if (empty($table)) {
  103. return '';
  104. }
  105. $this->_create_table = "CREATE TABLE IF NOT EXISTS `{$table}`(" . PHP_EOL;
  106. $table_status = $this->show_table_status($table);
  107. $columns = $this->show_columns($table);
  108. foreach ($columns AS $col) {
  109. $this->_create_table .= "`{$col['Field']}` {$col['Type']} NOT NULL {$col['Extra']}," . PHP_EOL;
  110. }
  111. $this->_create_table .= $this->create_indexSyntax($table);
  112. $char = substr($table_status['Collation'], 0, strpos($table_status['Collation'], '_'));
  113. $table_status['Auto_increment'] = $table_status['Auto_increment'] ? $table_status['Auto_increment'] : 0;
  114. $this->_create_table .= ")Engine={$table_status['Engine']} AUTO_INCREMENT={$table_status['Auto_increment']} DEFAULT CHARSET={$char};" . str_repeat(PHP_EOL, 3);
  115. return $this->_create_table;
  116. }
  117. /**
  118. * 显示触发器
  119. */
  120. public function show_constraint($db_name) {
  121. if (empty($db_name)) {
  122. return array();
  123. }
  124. $sql = "SELECT a.CONSTRAINT_NAME AS constrint_name, a.TABLE_name AS table_name, a.COLUMN_NAME AS column_name, a.REFERENCED_TABLE_NAME as referenced_table_name, a.REFERENCED_COLUMN_NAME AS referenced_column_name, b.UPDATE_RULE as update_rule, b.DELETE_RULE AS delete_rule FROM information_schema.KEY_COLUMN_USAGE AS a LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS AS b ON a.constraint_name=b.constraint_name WHERE a.constraint_schema = '{$db_name}' AND a.POSITION_IN_UNIQUE_CONSTRAINT = 1";
  125. $result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  126. }
  127. /**
  128. * 显示索引
  129. */
  130. public function show_index($table) {
  131. if (empty($table)) {
  132. return array();
  133. }
  134. $sql = "SHOW INDEX FROM {$table}";
  135. $result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  136. return $result;
  137. }
  138. /**
  139. * 显示数据库结构
  140. */
  141. public function show_database_char() {
  142. $sql = "SHOW VARIABLES LIKE 'character_set_database'";
  143. $char = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  144. return reset($char);
  145. }
  146. /**
  147. * 创建索引语法
  148. */
  149. public function create_indexSyntax($table) {
  150. if (empty($table)) {
  151. return array();
  152. }
  153. $indexing = $this->show_index($table);
  154. $syntax = array();
  155. $indexSyntax = array();
  156. foreach ($indexing as $index) {
  157. $syntax[$index['Index_type']][$index['Key_name']][] = $index['Column_name'];
  158. }
  159. foreach ($syntax as $index_type => $index_value) {
  160. foreach ($index_value as $key_name => $columns) {
  161. if ($key_name == 'PRIMARY') {
  162. $indexSyntax[] = 'PRIMARY KEY (`' . implode("`,`", $columns) . '`)';
  163. } else {
  164. if ($index_type == 'FULLTEXT') {
  165. $indexSyntax[] = "FULLTEXT KEY `{$key_name}` (`" . implode("`,`", $columns) . '`)';
  166. } else{
  167. $indexSyntax[] = "KEY `{$key_name}` USING {$index_type} (`" . implode("`,`", $columns) . '`)';
  168. }
  169. }
  170. }
  171. }
  172. return implode(',' . PHP_EOL, $indexSyntax) . PHP_EOL;
  173. }
  174. /**
  175. * 创建 insert 语法
  176. */
  177. public function create_insertSyntax($table) {
  178. if (empty($table)) {
  179. return '';
  180. }
  181. $sql = "SELECT * FROM {$table}";
  182. $result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
  183. $insertStr = '';
  184. if ($result) {
  185. $first = reset($result);
  186. $key = implode('`,`', array_keys($first));
  187. $insert = "INSERT INTO `{$table}` (`{$key}`) VALUES ";
  188. $valuesStr = array();
  189. foreach ($result as $value) {
  190. $values = array();
  191. foreach ($value as $v) {
  192. $v = mysql_real_escape_string($v);
  193. $values[] = preg_replace("#\\\+#", "\\", $v);
  194. }
  195. $valuesStr[] = "('" . implode("','", $values) . "')";
  196. }
  197. $valuesStr = array_chunk($valuesStr, 5000);
  198. foreach ($valuesStr as $str) {
  199. $insertStr .= $insert . implode(',', $str) . ';' . PHP_EOL;
  200. }
  201. }
  202. return $insertStr . str_repeat(PHP_EOL, 3);
  203. }
  204. }
  205. $export = '';
  206. $test = new MysqlExport('localhost', 'root', '', 'pm_cms');
  207. $char = $test->show_database_char();
  208. $test->query("SET NAMES {$char['Value']}");
  209. $tables = $test->show_tables();
  210. foreach ($tables as $table) {
  211. list($table_name) = array_values($table);
  212. $export .= $test->show_create_table($table_name);
  213. $export .= $test->create_insertSyntax($table_name);
  214. }
  215. $fp = fopen('pm_cms.sql', 'w');
  216. fwrite($fp, $export);
  217. fclose($fp);
  218. ?>
复制代码


热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

178

2026.01.28

包子漫画在线官方入口大全
包子漫画在线官方入口大全

本合集汇总了包子漫画2026最新官方在线观看入口,涵盖备用域名、正版无广告链接及多端适配地址,助你畅享12700+高清漫画资源。阅读专题下面的文章了解更多详细内容。

35

2026.01.28

ao3中文版官网地址大全
ao3中文版官网地址大全

AO3最新中文版官网入口合集,汇总2026年主站及国内优化镜像链接,支持简体中文界面、无广告阅读与多设备同步。阅读专题下面的文章了解更多详细内容。

79

2026.01.28

php怎么写接口教程
php怎么写接口教程

本合集涵盖PHP接口开发基础、RESTful API设计、数据交互与安全处理等实用教程,助你快速掌握PHP接口编写技巧。阅读专题下面的文章了解更多详细内容。

2

2026.01.28

php中文乱码如何解决
php中文乱码如何解决

本文整理了php中文乱码如何解决及解决方法,阅读节专题下面的文章了解更多详细内容。

4

2026.01.28

Java 消息队列与异步架构实战
Java 消息队列与异步架构实战

本专题系统讲解 Java 在消息队列与异步系统架构中的核心应用,涵盖消息队列基本原理、Kafka 与 RabbitMQ 的使用场景对比、生产者与消费者模型、消息可靠性与顺序性保障、重复消费与幂等处理,以及在高并发系统中的异步解耦设计。通过实战案例,帮助学习者掌握 使用 Java 构建高吞吐、高可靠异步消息系统的完整思路。

8

2026.01.28

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

24

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

122

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

72

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
MySQL 教程
MySQL 教程

共48课时 | 2万人学习

Java 教程
Java 教程

共578课时 | 52.6万人学习

国外Web开发全栈课程全集
国外Web开发全栈课程全集

共12课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号