说明,该类适用于小型的网站的数据库教程备份,内置mysql连接,只需要简单配置数据连接及存贮备份的位置即可.
类中show_dir_file() 方法可直接返回备份目录下的所有文件,返回以数组形式.
方法 expord_sql() 直接生成sql文件,该类制作简单,可任意传播,如何您对该类有什么提议,请发送邮件给小虾.
mysql 数据备份类代码如下:
- 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";
-
-
-
- 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");
- }
-
-
-
- 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;
- }
-
-
-
- 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);
- }
-
-
-
- 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]);
- }
- $file = $this->data_dir.$this->data_name;
- $link = fopen($file,"w+");
- if(!is_writable($file)){
- echo "文件不可写";
- exit();
- }
- fwrite($link,$tables);
- fclose($link);
- echo "备份成功";
- }
- }
|