mysql 数据备份类代码
说明,该类适用于小型的网站的数据库教程备份,内置mysql连接,只需要简单配置数据连接及存贮备份的位置即可.
类中show_dir_file() 方法可直接返回备份目录下的所有文件,返回以数组形式.
方法 expord_sql() 直接生成sql文件,该类制作简单,可任意传播,如何您对该类有什么提议,请发送邮件给小虾.
mysql 数据备份类代码如下:
<?php class data { public $data_dir = "class/"; //备份文件存放的路径 public $data_name = "111cnnet.sql"; //备份文件名 private $mysql_host = "localhost"; //数据库地址 private $mysql_user = "root"; //用户名 private $mysql_pwd = "lpl19881129"; //密码 private $mysql_db = "date"; //数据库名 private $mysql_code = "gbk"; //编码方式 /*** * 1.连接数据库 * **/ function __construct() { $conn = mysql_connect($this->mysql_host, $this->mysql_user, $this->mysql_pwd); mysql_select_db($this->mysql_db); mysql_query("set names $this->mysql_code"); } /*** * 2.生成sql语句 * **/ private function set_sql($table) { $tabledump = "drop table if exists $table; "; $createtable = mysql_query("show create table $table"); $create = mysql_fetch_row($createtable); $tabledump.= $create[1] . "; "; $rows = mysql_query("select * from $table"); $numfields = mysql_num_fields($rows); $numrows = mysql_num_rows($rows); while ($row = mysql_fetch_row($rows)) { $comma = ""; $tabledump.= "insert into $table values("; for ($i = 0; $i < $numfields; $i++) { $tabledump.= $comma . "'" . mysql_escape_string($row[$i]) . "'"; $comma = ","; } $tabledump.= "); "; } $tabledump.= " "; return $tabledump; } /*** * 3.显示存放目录下已经备份的文件 * **/ public function show_dir_file() { $dir = $this->data_dir; if (!is_dir($dir)) { if (!mkdir($dir)) { echo "文件夹不存在,尝试创建文件夹,创建失败,可能是您没有相关权限"; exit(); } else { chmod($dir, 755); } } if (!is_writable($dir)) { echo " 文件不可写"; exit(); } $link = opendir($dir); if (!$link) { echo "创建链接失败"; exit(); } return scandir($dir); } /*** * 4.生成sql文件 * **/ public function expord_sql() { $this->show_dir_file(); $result = mysql_list_tables($this->mysql_db); while ($arr = mysql_fetch_row($result)) { $tables.= $this->set_sql($arr[0]); } //开源代码phprm.com $file = $this->data_dir . $this->data_name; $link = fopen($file, "w+"); if (!is_writable($file)) { echo "文件不可写"; exit(); } fwrite($link, $tables); fclose($link); echo "备份成功"; } }
文章地址:http://www.phprm.com/mxdx/fs5425.html
转载随意^^请带上本文地址!