數(shù)據(jù)庫備份類我們只要在網(wǎng)上一搜索在N多的類代碼,下面我來總結(jié)幾款不錯數(shù)據(jù)庫備份希望對大家有所幫助.
數(shù)據(jù)庫備份類,使用方法,代碼如下:
- require_once("backdata.class.php");
- $link = @mysql_connect("localhost","數(shù)據(jù)庫名","密碼") or die ('Could not connect to server.');
- mysql_query("use cms",$link);
- mysql_query("set names utf8",$link);
- //開源代碼Vevb.com
- $dbbck = new backupData($link);//實例化它,只要一個鏈接標(biāo)識就行了
- //備份數(shù)據(jù)時,如想備份一個數(shù)據(jù)庫中的所有表,你可這樣寫:
- $dbbck->backupTables("cms","./",array('*'));
- //備份數(shù)據(jù)時,如想備份一個數(shù)據(jù)庫中的僅一個表時,你可這樣寫:
- $dbbck->backupTables("cms","./",array('user'));
- //備份數(shù)據(jù)時,如想備份一個數(shù)據(jù)庫中的多個表時,你可這樣寫:
- $dbbck->backupTables("cms","./",array('user','acl','informatoin'));
- //注解:$dbbck->backupTables("參1","參2",array());中,
參1為:數(shù)據(jù)庫名
參2為:要存放備份數(shù)據(jù)的位置(即目錄地址)
第三個為:你要保存那些表
backdata.class.php,代碼如下:
- <?php
- /*
- *
- *一個簡單的Mysql備份數(shù)據(jù)類
- *
- */
- class backupData{
- private $mysql_link;//鏈接標(biāo)識
- private $dbName; //數(shù)據(jù)庫名
- private $dataDir; //數(shù)據(jù)所要存放的目錄
- 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";
- //讀取表結(jié)構(gòu)
- $rs = mysql_query("SHOW CREATE TABLE $tablename",$this->mysql_link);
- $row=mysql_fetch_row($rs);
- //獲得表結(jié)構(gòu)組成SQL
- $sqls.=$row['1'].";nn";
- unset($rs);
- unset($row);
- //************************以下是形成SQL的后半部分**************
- //查尋出表中的所有數(shù)據(jù)
- $rs=mysql_query("select * from $tablename",$this->mysql_link);
- //表的字段個數(shù)
- $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){ //處理傳入進(jìn)來的數(shù)組
- foreach($array as $tables){
- if($tables=='*'){ //所有的表(獲得表名時不能按常規(guī)方式來組成一個數(shù)組)
- $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;
- }
- }
- ?>
新聞熱點
疑難解答