php类实现MySQL数据库备份、还原
这是一个非常简单的利用php来备份mysql数据库的类文件,我们只要简单的在dbmange中配置好连接地址用户名与数据库即可,下面我们一起来看这个例子,代码如下:
- <?php
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- class DBManage
- {
- var $db;
- var $database;
- var $sqldir;
- var $record;
-
- private $ds = "n";
-
- public $sqlContent = "";
-
- public $sqlEnd = ";";
-
-
-
-
-
-
-
-
-
- function __construct($host = 'localhost', $username = 'root', $password = '', $thisatabase = 'test', $charset = 'utf8')
- {
- $this->host = $host;
- $this->username = $username;
- $this->password = $password;
- $this->database = $thisatabase;
- $this->charset = $charset;
-
- $this->db = mysql_connect ( $this->host, $this->username, $this->password ) or die ( "数据库连接失败." );
-
- mysql_select_db ( $this->database, $this->db ) or die ( "无法打开数据库" );
-
- mysql_query ( 'SET NAMES ' . $this->charset, $this->db );
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- function backup($tablename = '', $dir = '', $size = 2000)
- {
-
-
- $sql = '';
-
- if (! emptyempty ( $tablename ))
- {
- echo '正在备份表' . $tablename . '<br />';
-
- $sql = $this->_retrieve();
-
- $sql .= $this->_insert_table_structure ( $tablename );
-
- $data = mysql_query ( "select * from " . $tablename );
-
- $filename = date ( 'YmdHis' ) . "_" . $tablename;
-
- $num_fields = mysql_num_fields ( $data );
-
- $p = 1;
-
- while ( $record = mysql_fetch_array ( $data ) )
- {
-
- $sql .= $this->_insert_record ( $tablename, $num_fields, $record );
-
- if (strlen ( $sql ) >= $size * 1000)
- {
- $file = $filename . "_v" . $p . ".sql";
- if ($this->_write_file ( $sql, $file, $dir ))
- {
- echo "表-" . $tablename . "-卷-" . $p . "-数据备份完成,生成备份文件 <span style='color:#f00;'>$dir$filename</span><br />";
- }
- else
- {
- echo "备份表-" . $tablename . "-失败<br />";
- }
-
- $p ++;
-
- $sql = "";
- }
- }
-
- if ($sql != "")
- {
- $filename .= "_v" . $p . ".sql";
- if ($this->_write_file ( $sql, $filename, $dir ))
- {
- echo "表-" . $tablename . "-卷-" . $p . "-数据备份完成,生成备份文件 <span style='color:#f00;'>$dir$filename</span><br />";
- }
- else
- {
- echo "备份卷-" . $p . "-失败<br />";
- }
- }
- }
- else
- {
- if ($tables = mysql_query ( "show table status from " . $this->database ))
- {
- echo "读取数据库结构成功!<br />";
- }
- else
- {
- exit ( "读取数据库结构成功!<br />" );
- }
-
- $sql .= $this->_retrieve();
-
- $filename = date ( 'YmdHis' ) . "_all";
-
- $tables = mysql_query ( 'SHOW TABLES' );
-
- $p = 1;
-
- while ( $table = mysql_fetch_array ( $tables ) ) <