php備份mysql資料庫程式碼

來源:互聯網
上載者:User

先看備份的類檔案

backdata.class.php:

 代碼如下 複製代碼

<?php
/*
*
*簡單的一個Mysql備份資料類
*
*/
class backupData{
    private    $mysql_link;//連結標識
    private    $dbName;    //資料庫名
    private    $dataDir;     //資料所要存放的目錄
    private    $tableNames;//表名

    public function __construct($mysql_link){
         $this->mysql_link = $mysql_link;
    }
    public function backupTables($dbName,$dataDir,$tableNames){//開始備份
        $this->dbName  = $dbName;
        $this->dataDir  = $dataDir;
        $this->tableNames = $tableNames;
        $tables=$this->delarray($this->tableNames);
        $sqls='';
        foreach($tables as $tablename){
            if($tablename==''){//表不存在時
                continue;
            }
           
            //************************以下是形成SQL的前半部分**************
            //如果存在表,就先刪除
            $sqls .= "DROP TABLE IF EXISTS $tablename;n";
            //讀取表結構
            $rs = mysql_query("SHOW CREATE TABLE $tablename",$this->mysql_link); 
            $row=mysql_fetch_row($rs);
            //獲得表結構組成SQL
            $sqls.=$row['1'].";nn";
            unset($rs);
            unset($row);
           
            //************************以下是形成SQL的後半部分**************
            //查尋出表中的所有資料
            $rs=mysql_query("select * from $tablename",$this->mysql_link);
            //表的欄位個數
            $field=mysql_num_fields($rs);
            //形成此種SQL語句:"INSERT INTO `groups` VALUES('1499e0ca25988d','主任','','0');"
            while($rows=mysql_fetch_row($rs)){
                $comma='';//逗號
                $sqls.="INSERT INTO `$tablename` VALUES(";
                for($i=0;$i<$field;$i++){
                    $sqls.=$comma."'".$rows[$i]."'";
                    $comma=',';
                }
                $sqls.=");nnn";
            }
        }
        $backfilepath=$this->dataDir.date("Ymdhis",time()).'.sql';
       
        //寫入檔案
        $filehandle = fopen($backfilepath, "w");
        fwrite($filehandle, $sqls);
        fclose($filehandle);
    }
    private function delarray($array){    //處理傳入進來的數組
        foreach($array as $tables){
            if($tables=='*'){    //所有的表(獲得表名時不能按常規方式來組成一個數組)
                $newtables=mysql_list_tables($this->dbName,$this->mysql_link);
                $tableList = array();
                for ($i = 0; $i < mysql_numrows($newtables); $i++){
                    array_push($tableList,mysql_tablename($newtables, $i));
                }
                $tableList=$tableList;
            }else{
                $tableList=$array;
                break;
            }
        }
        return $tableList;
    }
}

?>

Database Backup用法

 

 代碼如下 複製代碼
require_once("backdata.class.php");
$link = @mysql_connect("localhost","資料庫名","密碼") or die ('Could not connect to server.');
mysql_query("use cms",$link);
mysql_query("set names utf8",$link);
$dbbck=new backupData($link);//執行個體化它,只要一個連結標識就行了
//備份資料時,如想備份一個資料庫中的所有表,你可這樣寫:
$dbbck->backupTables("cms","./",array('*'));
//備份資料時,如想備份一個資料庫中的僅一個表時,你可這樣寫:
$dbbck->backupTables("cms","./",array('user'));
//備份資料時,如想備份一個資料庫中的多個表時,你可這樣寫:
$dbbck->backupTables("cms","./",array('user','acl','informatoin'));
//註解:$dbbck->backupTables("參1","參2",array());中,
參1為:資料庫名,
參2為:要存放備份資料的位置(即目錄位址)
第三個為:你要儲存那些表


再來分享一個Database Backup類

 代碼如下 複製代碼

/**
  * 說明,該類適用於小型的網站的Database Backup,內建mysql串連,只需要簡單配置資料連線
  * 及存貯備份的位置即可。
  * 類實列化並且串連資料庫以後可執行以下操作
  * get_db_table($database)    取得所有資料表
  * export_sql($table,$subsection=0))   產生sql檔案,注意產生sql檔案只儲存到伺服器目錄,不提供下載
  * import_sql($dir)     恢複資料只匯入伺服器目錄下的sql檔案
  * 該類製作簡單,可任意傳播,如何您對該類有什麼提議,請發送郵件給小蝦
  * @author 趙紅健[遊天小蝦]
  * email:328742379@qq.com
  * qq交流群:69574955 聚義堂-網頁製作交
  */

class data {
 public   $data_dir    = "class/"; //備份檔案存放的路徑
 public   $transfer     ="";   //臨時存放sql[切勿不要對該屬性賦值,否則會建置錯誤的sql語句]

/**
 *資料庫連接
 *@param string $host 資料庫主機名稱
 *@param string $user 使用者名稱
 *@param string $pwd  密碼
 *@param string $db   選擇資料庫名
 *@param string $charset 編碼方式
 */
 function connect_db($host,$user,$pwd,$db,$charset='gbk'){
  if(!$conn = mysql_connect($host,$user,$pwd)){
   return false;
  }
  mysql_select_db($db);
  mysql_query("set names $charset");
  return true;
 }

/**
 * 產生sql語句
 * @param   $table     要備份的表
 * @return  $tabledump 產生的sql語句
 */
 public function set_sql($table,$subsection=0,&$tabledom=''){
  $tabledom .= "drop table if exists $tablen";
  $createtable = mysql_query("show create table $table");
  $create = mysql_fetch_row($createtable);
  $create[1] = str_replace("n","",$create[1]);
  $create[1] = str_replace("t","",$create[1]);

  $tabledom  .= $create[1].";n";

  $rows = mysql_query("select * from $table");
  $numfields = mysql_num_fields($rows);
  $numrows = mysql_num_rows($rows);
  $n = 1;
  $sqlarry = array();
  while ($row = mysql_fetch_row($rows)){
     $comma = "";
     $tabledom  .= "insert into $table values(";
     for($i = 0; $i < $numfields; $i++)
     {
    $tabledom  .= $comma."'".mysql_escape_string($row[$i])."'";
    $comma = ",";
     }
    $tabledom  .= ")n";
     if($subsection != 0 && strlen($this->transfer )>=$subsection*1000){
       $sqlarry[$n]= $tabledom;
       $tabledom = ''; $n++;
     }
  }
  return $sqlarry;
   }

/**
 *列表資料庫中的表
 *@param  database $database 要操作的資料庫名
 *@return array    $dbarray  所列表的資料庫表
 */
 public function get_db_table($database){
  $result = mysql_list_tables($database);
  while($tmparry = mysql_fetch_row($result)){
   $dbarry[]  = $tmparry[0];
  }
  return $dbarry;
 }

/**
 *驗證目錄是否有效
 *@param diretory $dir
 *@return booln
 */
 function check_write_dir($dir){
  if(!is_dir($dir)) {@mkdir($dir, 0777);}
  if(is_dir($dir)){
   if($link = opendir($dir)){
    $filearry = scandir($dir);
    for($i=0;$i<count($filearry);$i++){
     if($filearry[$i]!='.' || $filearry != '..'){
      @unlink($dir.$filearry[$i]);
     }
    }
   }
  }
  return true;
 }
/**
 *將資料寫入到檔案中
 *@param file $filename 檔案名稱
 *@param string $str   要寫入的資訊
 *@return booln 寫入成功則返回true,否則false
 */
 private function write_sql($filename,$str){
  $re= true;
  if(!@$fp=fopen($filename,"w+")) {$re=false; echo "在開啟檔案時遇到錯誤,備份失敗!";}
  if(!@fwrite($fp,$str)) {$re=false; echo "在寫入資訊時遇到錯誤,備份失敗!";}
  if(!@fclose($fp)) {$re=false; echo "在關閉檔案 時遇到錯誤,備份失敗!";}
  return $re;
 }

/**
 *產生sql檔案
 *@param string $sql sql    語句
 *@param number $subsection 分卷大小,以kb為單位,為0表示不分卷
 */
     public function export_sql($table,$subsection=0){
      if(!$this->check_write_dir($this->data_dir)){echo '您沒有許可權操作目錄,備份失敗';return false;}
      if($subsection == 0){
       if(!is_array($table)){
    $this->set_sql($table,0,$this->transfer);
   }else{
    for($i=0;$i<count($table);$i++){
     $this->set_sql($table[$i],0,$this->transfer);
    }
   }
       $filename = $this->data_dir.date("ymd",time()).'_all.sql';
       if(!$this->write_sql($filename,$this->transfer)){return false;}
      }else{
       if(!is_array($table)){
    $sqlarry = $this->set_sql($table,$subsection,$this->transfer);
    $sqlarry[] = $this->transfer;
   }else{
    $sqlarry = array();
    for($i=0;$i<count($table);$i++){
     $tmparry = $this->set_sql($table[$i],$subsection,$this->transfer);
     $sqlarry = array_merge($sqlarry,$tmparry);
    }
    $sqlarry[] = $this->transfer;
   }
       for($i=0;$i<count($sqlarry);$i++){
        $filename = $this->data_dir.date("ymd",time()).'_part'.$i.'.sql';
        if(!$this->write_sql($filename,$sqlarry[$i])){return false;}
       }
      }
      return true;
    }
/**
 *載入sql檔案
 *@param diretory $dir
 *@return booln
 *注意:請不在目錄下面存放其它檔案,或者目錄
 *以節省恢復
 */
    public function import_sql($dir){
  if($link = opendir($dir)){
   $filearry = scandir($dir);
    $pattern = "_part[0-9]+.sql$|_all.sql$";
   for($i=0;$i<count($filearry);$i++){
    if(eregi($pattern,$filearry[$i])){
     $sqls=file($dir.$filearry[$i]);
     foreach($sqls as $sql){
      str_replace("r","",$sql);
      str_replace("n","",$sql);
      if(!mysql_query(trim($sql))) return false;
     }
    }
   }
   return true;
  }
    }

}
 

應用方法

 代碼如下 複製代碼

//$d = new data();

//串連資料庫
//if(!$d->connect_db('localhost','root','','guestbook','gbk')){
// echo '資料庫連接失敗';
//}

//尋找資料庫內所有資料表
//$tablearry = $d->get_db_table('guestbook');

//備份並產生sql檔案
//if(!$d->export_sql($tablearry)){
// echo '備份失敗';
//}else{
// echo '備份成功';
//}

//恢複匯入sql檔案夾
//if($d->import_sql($d->data_dir)){
// echo '恢複成功';
//}else{
// 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.