mysql 資料備份類代碼

來源:互聯網
上載者:User

 /***
  * 說明,該類適用於小型的網站的資料庫教程備份,內建mysql串連,只需要簡單配置資料連線
  * 及存貯備份的位置即可。
  * 類中show_dir_file() 方法可直接返回備份目錄下的所有檔案,返回以數組形式
  * 方法 expord_sql() 直接產生sql檔案
  * 該類製作簡單,可任意傳播,如何您對該類有什麼提議,請發送郵件給小蝦
  * 製作人:遊天小蝦
  * emial:328742379@qq.com
  * **/

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]);
  }
  $file = $this->data_dir.$this->data_name;
  $link = fopen($file,"w+");
  if(!is_writable($file)){
   echo "檔案不可寫";
   exit();
  }
  fwrite($link,$tables);
  fclose($link);
  echo "備份成功";
    }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.