文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>php 备份数据库(生成word,excel,json,xml,sql)

php 备份数据库(生成word,excel,json,xml,sql)

时间:2011-01-12  来源:hand-LAMP

文章分类:PHP编程

单表备份

代码:

Php代码

  1. <?php  
  2. class Db  
  3. {  
  4.     var $conn;  
  5.   
  6.     function Db($host="localhost",$user="root",$pass="root",$db="test")  
  7.     {  
  8.       if(!$this->conn=mysql_connect($host,$user,$pass))  
  9.       die("can't connect to mysql sever");  
  10.       mysql_select_db($db,$this->conn);  
  11.       mysql_query("SET NAMES 'UTF-8'");  
  12.     }  
  13.   
  14.     function execute($sql)  
  15.     {  
  16.        return mysql_query($sql,$this->conn);  
  17.     }  
  18.   
  19.     function findCount($sql)  
  20.     {  
  21.         $result=$this->execute($sql);  
  22.         return mysql_num_rows($result);  
  23.     }  
  24.   
  25.     function findBySql($sql)  
  26.     {  
  27.         $array=array();  
  28.         $result=mysql_query($sql);  
  29.         $i=0;  
  30.         while($row=mysql_fetch_assoc($result))  
  31.            {  
  32.           $array[$i]=$row;   
  33.        $i++;  
  34.            }  
  35.         return $array;  
  36.     }  
  37.   
  38.     //$con的几种情况  
  39.     //空:返回全部记录  
  40.     //array:eg. array('id'=>'1') 返回id=1的记录  
  41.     //string :eg. 'id=1' 返回id=1的记录  
  42.     function toExtJson($table,$start="0",$limit="10",$cons="")  
  43.     {  
  44.        $sql=$this->generateSql($table,$cons);  
  45.        $totalNum=$this->findCount($sql);  
  46.        $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit);  
  47.        $resultNum = count($result);//当前结果数  
  48.       $str="";  
  49.       $str.= "{";  
  50.       $str.= "'totalCount':'$totalNum',";  
  51.       $str.="'rows':";  
  52.       $str.="[";  
  53.       for($i=0;$i<$resultNum;$i++){  
  54.        $str.="{";   
  55.        $count=count($result[$i]);  
  56.        $j=1;  
  57.        foreach($result[$i] as $key=>$val)  
  58.        {  
  59.        if($j<$count)  
  60.        {  
  61.        $str.="'".$key."':'".$val."',";  
  62.        }  
  63.        elseif($j==$count)  
  64.        {  
  65.        $str.="'".$key."':'".$val."'";  
  66.        }  
  67.        $j++;  
  68.                 }  
  69.          
  70.        $str.="}";  
  71.        if ($i != $resultNum-1) {  
  72.                  $str.= ",";  
  73.              }  
  74.       }  
  75.       $str.="]";  
  76.       $str.="}";  
  77.       return $str;    
  78.     }  
  79.   
  80.     function generateSql($table,$cons)  
  81.     {  
  82.         $sql="";//sql条件  
  83.        $sql="select * from ".$table;  
  84.        if($cons!="")  
  85.        {  
  86.        if(is_array($cons))  
  87.        {  
  88.          $k=0;  
  89.          foreach($cons as $key=>$val)  
  90.       {  
  91.       if($k==0)  
  92.       {  
  93.       $sql.="where '";  
  94.       $sql.=$key;  
  95.       $sql.="'='";  
  96.       $sql.=$val."'";  
  97.       }else  
  98.       {  
  99.       $sql.="and '";  
  100.       $sql.=$key;  
  101.       $sql.="'='";  
  102.       $sql.=$val."'";  
  103.       }  
  104.       $k++;  
  105.       }  
  106.        }else  
  107.        {  
  108.        $sql.=" where ".$cons;  
  109.        }  
  110.        }  
  111.        return $sql;  
  112.     }  
  113.   
  114.     function toExtXml($table,$start="0",$limit="10",$cons="")  
  115.     {  
  116.        $sql=$this->generateSql($table,$cons);  
  117.        $totalNum=$this->findCount($sql);  
  118.        $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit);  
  119.        $resultNum = count($result);//当前结果数  
  120.        header("Content-Type: text/xml");  
  121.        $xml="<?xml version=\"1.0\"  encoding=\"utf-8\" ?>\n";  
  122.        $xml.="<xml>\n";  
  123.        $xml.="\t<totalCount>".$totalNum."</totalCount>\n";  
  124.        $xml.="\t<items>\n";  
  125.        for($i=0;$i<$resultNum;$i++){  
  126.        $xml.="\t\t<item>\n";  
  127.        foreach($result[$i] as $key=>$val)  
  128.        $xml.="\t\t\t<".$key.">".$val."</".$key.">\n";  
  129.        $xml.="\t\t</item>\n";  
  130.        }  
  131.         $xml.="\t</items>\n";  
  132.         $xml.="</xml>\n";  
  133.         return $xml;  
  134.     }  
  135.   
  136.     //输出word表格  
  137.     function toWord($table,$mapping,$fileName)  
  138.     {  
  139.        header('Content-type: application/doc');   
  140.           header('Content-Disposition: attachment; filename="'.$fileName.'.doc"');   
  141.           echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"   
  142.            xmlns:w="urn:schemas-microsoft-com:office:word"   
  143.            xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">  
  144.         <head>  
  145.            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
  146.         <title>'.$fileName.'</title>  
  147.         </head>  
  148.         <body>';   
  149.         echo'<table border=1><tr>';  
  150.         if(is_array($mapping))  
  151.         {  
  152.           foreach($mapping as $key=>$val)  
  153.        echo'<td>'.$val.'</td>';  
  154.         }  
  155.         echo'</tr>';  
  156.         $results=$this->findBySql('select * from '.$table);  
  157.         foreach($results as $result)  
  158.         {  
  159.           echo'<tr>';  
  160.           foreach($result as $key=>$val)  
  161.        echo'<td>'.$val.'</td>';  
  162.        echo'</tr>';  
  163.         }  
  164.         echo'</table>';  
  165.         echo'</body>';  
  166.         echo'</html>';  
  167.     }  
  168.   
  169.     function toExcel($table,$mapping,$fileName)  
  170.     {  
  171.       header("Content-type:application/vnd.ms-excel");  
  172.          header("Content-Disposition:filename=".$fileName.".xls");  
  173.       echo'<html xmlns:o="urn:schemas-microsoft-com:office:office"  
  174.            xmlns:x="urn:schemas-microsoft-com:office:excel"  
  175.            xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">  
  176.            <head>  
  177.            <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">  
  178.            <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">  
  179.            <!--[if gte mso 9]><xml>  
  180.            <x:ExcelWorkbook>  
  181.                <x:ExcelWorksheets>  
  182.                        <x:ExcelWorksheet>  
  183.                            <x:Name></x:Name>  
  184.                            <x:WorksheetOptions>  
  185.                                <x:DisplayGridlines/>  
  186.                            </x:WorksheetOptions>  
  187.                        </x:ExcelWorksheet>  
  188.                </x:ExcelWorksheets>  
  189.            </x:ExcelWorkbook>  
  190.            </xml><![endif]-->  
  191.            </head>  
  192.         <body link=blue vlink=purple leftmargin=0 topmargin=0>';   
  193.         echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">';  
  194.            echo'<tr>';  
  195.         if(is_array($mapping))  
  196.         {  
  197.           foreach($mapping as $key=>$val)  
  198.        echo'<td>'.$val.'</td>';  
  199.         }  
  200.         echo'</tr>';  
  201.         $results=$this->findBySql('select * from '.$table);  
  202.         foreach($results as $result)  
  203.         {  
  204.           echo'<tr>';  
  205.           foreach($result as $key=>$val)  
  206.        echo'<td>'.$val.'</td>';  
  207.        echo'</tr>';  
  208.         }  
  209.         echo'</table>';  
  210.         echo'</body>';  
  211.         echo'</html>';  
  212.     }  
  213.   
  214.     function Backup($table)  
  215.     {  
  216.       if(is_array ($table))  
  217.       {  
  218.        $str="";  
  219.        foreach($table as $tab)  
  220.        $str.=$this->get_table_content($tab);  
  221.        return $str;  
  222.       }else{  
  223.        return $this->get_table_content($table);  
  224.       }  
  225.     }  
  226.   
  227.     function Backuptofile($table,$file)  
  228.     {  
  229.       header("Content-disposition: filename=$file.sql");//所保存的文件名  
  230.       header("Content-type: application/octetstream");  
  231.       header("Pragma: no-cache");  
  232.       header("Expires: 0");  
  233.       if(is_array ($table))  
  234.       {  
  235.        $str="";  
  236.        foreach($table as $tab)  
  237.        $str.=$this->get_table_content($tab);  
  238.        echo $str;  
  239.       }else{  
  240.        echo $this->get_table_content($table);  
  241.       }  
  242.     }  
  243.   
  244.     function Restore($table,$file="",$content="")  
  245.     {  
  246.       //排除file,content都为空或者都不为空的情况  
  247.       if(($file==""&&$content=="")||($file!=""&&$content!=""))  
  248.       echo"参数错误";  
  249.       $this->truncate($table);  
  250.       if($file!="")  
  251.       {  
  252.        if($this->RestoreFromFile($file))  
  253.        return true;  
  254.        else  
  255.        return false;  
  256.       }  
  257.       if($content!="")  
  258.       {  
  259.        if($this->RestoreFromContent($content))  
  260.        return true;  
  261.        else  
  262.        return false;  
  263.       }  
  264.     }  
  265.   
  266.     //清空表,以便恢复数据  
  267.     function truncate($table)  
  268.     {  
  269.       if(is_array ($table))  
  270.       {  
  271.        $str="";  
  272.        foreach($table as $tab)  
  273.        $this->execute("TRUNCATE TABLE $tab");  
  274.       }else{  
  275.        $this->execute("TRUNCATE TABLE $table");  
  276.       }  
  277.     }  
  278.   
  279.     function get_table_content($table)  
  280.     {  
  281.       $results=$this->findBySql("select * from $table");  
  282.       $temp = "";  
  283.       $crlf="<br>";  
  284.       foreach($results as $result)  
  285.       {  
  286.          
  287.          
  288.       $schema_insert = "INSERT INTO  $table VALUES (";  
  289.       foreach($result as $key=>$val)  
  290.       {  
  291.        if($val != "")  
  292.        $schema_insert .= " '".addslashes($val)."',";  
  293.        else  
  294.        $schema_insert .= "NULL,";  
  295.       }  
  296.       $schema_insert = ereg_replace(",$", "", $schema_insert);  
  297.       $schema_insert .= ");$crlf";  
  298.       $temp = $temp.$schema_insert ;  
  299.       }  
  300.       return $temp;  
  301.     }  
  302.   
  303.     function RestoreFromFile($file){  
  304.       if (false !== ($fp = fopen($file, 'r'))) {  
  305.        $sql_queries = trim(fread($fp, filesize($file)));  
  306.        $this->splitMySqlFile($pieces, $sql_queries);  
  307.        foreach ($pieces as $query) {  
  308.         if(!$this->execute(trim($query)))  
  309.         return false;  
  310.        }  
  311.        return true;  
  312.       }  
  313.       return false;  
  314.     }  
  315.   
  316.     function RestoreFromContent($content)  
  317.     {  
  318.       $content = trim($content);  
  319.       $this->splitMySqlFile($pieces, $content);  
  320.       foreach ($pieces as $query) {  
  321.        if(!$this->execute(trim($query)))  
  322.        return false;  
  323.       }  
  324.       return true;  
  325.     }  
  326.   
  327.     function splitMySqlFile(&$ret, $sql)  
  328.     {  
  329.       $sql= trim($sql);  
  330.       $sql=split(';',$sql);  
  331.       $arr=array();  
  332.       foreach($sql as $sq)  
  333.       {  
  334.         if($sq!="");  
  335.         $arr[]=$sq;  
  336.       }  
  337.       $ret=$arr;  
  338.       return true;  
  339.     }  
  340. }  
  341.   
  342.   
  343. $db=new db();  
  344.   
  345. // 生成 word   
  346. //$map=array('No','Name','Email','Age');  
  347. //echo  $db->toWord('test',$map,'档案');  
  348.   
  349. // 生成 Excel   
  350. //$map=array('No','Name','Email','Age');  
  351. //echo  $db->toExcel('test',$map,'档案');  
  352.   
  353. // 生成 Xml   
  354. //echo  $db->toExtXml('test',0,20);  
  355.   
  356. // 生成 Json   
  357. //echo  $db->toExtJson('test',0,20);  
  358.   
  359. //备份      
  360. //echo $db->Backuptofile('test','backup');  
  361.   
  362.   
  363. ?>  
<?php class Db { var $conn; function Db($host="localhost",$user="root",$pass="root",$db="test") { if(!$this->conn=mysql_connect($host,$user,$pass)) die("can't connect to mysql sever"); mysql_select_db($db,$this->conn); mysql_query("SET NAMES 'UTF-8'"); } function execute($sql) { return mysql_query($sql,$this->conn); } function findCount($sql) { $result=$this->execute($sql); return mysql_num_rows($result); } function findBySql($sql) { $array=array(); $result=mysql_query($sql); $i=0; while($row=mysql_fetch_assoc($result)) { $array[$i]=$row; $i++; } return $array; } //$con的几种情况 //空:返回全部记录 //array:eg. array('id'=>'1') 返回id=1的记录 //string :eg. 'id=1' 返回id=1的记录 function toExtJson($table,$start="0",$limit="10",$cons="") { $sql=$this->generateSql($table,$cons); $totalNum=$this->findCount($sql); $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit); $resultNum = count($result);//当前结果数 $str=""; $str.= "{"; $str.= "'totalCount':'$totalNum',"; $str.="'rows':"; $str.="["; for($i=0;$i<$resultNum;$i++){ $str.="{"; $count=count($result[$i]); $j=1; foreach($result[$i] as $key=>$val) { if($j<$count) { $str.="'".$key."':'".$val."',"; } elseif($j==$count) { $str.="'".$key."':'".$val."'"; } $j++; } $str.="}"; if ($i != $resultNum-1) { $str.= ","; } } $str.="]"; $str.="}"; return $str; } function generateSql($table,$cons) { $sql="";//sql条件 $sql="select * from ".$table; if($cons!="") { if(is_array($cons)) { $k=0; foreach($cons as $key=>$val) { if($k==0) { $sql.="where '"; $sql.=$key; $sql.="'='"; $sql.=$val."'"; }else { $sql.="and '"; $sql.=$key; $sql.="'='"; $sql.=$val."'"; } $k++; } }else { $sql.=" where ".$cons; } } return $sql; } function toExtXml($table,$start="0",$limit="10",$cons="") { $sql=$this->generateSql($table,$cons); $totalNum=$this->findCount($sql); $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit); $resultNum = count($result);//当前结果数 header("Content-Type: text/xml"); $xml="<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"; $xml.="<xml>\n"; $xml.="\t<totalCount>".$totalNum."</totalCount>\n"; $xml.="\t<items>\n"; for($i=0;$i<$resultNum;$i++){ $xml.="\t\t<item>\n"; foreach($result[$i] as $key=>$val) $xml.="\t\t\t<".$key.">".$val."</".$key.">\n"; $xml.="\t\t</item>\n"; } $xml.="\t</items>\n"; $xml.="</xml>\n"; return $xml; } //输出word表格 function toWord($table,$mapping,$fileName) { header('Content-type: application/doc'); header('Content-Disposition: attachment; filename="'.$fileName.'.doc"'); echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>'.$fileName.'</title> </head> <body>'; echo'<table border=1><tr>'; if(is_array($mapping)) { foreach($mapping as $key=>$val) echo'<td>'.$val.'</td>'; } echo'</tr>'; $results=$this->findBySql('select * from '.$table); foreach($results as $result) { echo'<tr>'; foreach($result as $key=>$val) echo'<td>'.$val.'</td>'; echo'</tr>'; } echo'</table>'; echo'</body>'; echo'</html>'; } function toExcel($table,$mapping,$fileName) { header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=".$fileName.".xls"); echo'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]"> <head> <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT"> <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1"> <!--[if gte mso 9]><xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name></x:Name> <x:WorksheetOptions> <x:DisplayGridlines/> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml><![endif]--> </head> <body link=blue vlink=purple leftmargin=0 topmargin=0>'; echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">'; echo'<tr>'; if(is_array($mapping)) { foreach($mapping as $key=>$val) echo'<td>'.$val.'</td>'; } echo'</tr>'; $results=$this->findBySql('select * from '.$table); foreach($results as $result) { echo'<tr>'; foreach($result as $key=>$val) echo'<td>'.$val.'</td>'; echo'</tr>'; } echo'</table>'; echo'</body>'; echo'</html>'; } function Backup($table) { if(is_array ($table)) { $str=""; foreach($table as $tab) $str.=$this->get_table_content($tab); return $str; }else{ return $this->get_table_content($table); } } function Backuptofile($table,$file) { header("Content-disposition: filename=$file.sql");//所保存的文件名 header("Content-type: application/octetstream"); header("Pragma: no-cache"); header("Expires: 0"); if(is_array ($table)) { $str=""; foreach($table as $tab) $str.=$this->get_table_content($tab); echo $str; }else{ echo $this->get_table_content($table); } } function Restore($table,$file="",$content="") { //排除file,content都为空或者都不为空的情况 if(($file==""&&$content=="")||($file!=""&&$content!="")) echo"参数错误"; $this->truncate($table); if($file!="") { if($this->RestoreFromFile($file)) return true; else return false; } if($content!="") { if($this->RestoreFromContent($content)) return true; else return false; } } //清空表,以便恢复数据 function truncate($table) { if(is_array ($table)) { $str=""; foreach($table as $tab) $this->execute("TRUNCATE TABLE $tab"); }else{ $this->execute("TRUNCATE TABLE $table"); } } function get_table_content($table) { $results=$this->findBySql("select * from $table"); $temp = ""; $crlf="<br>"; foreach($results as $result) { $schema_insert = "INSERT INTO $table VALUES ("; foreach($result as $key=>$val) { if($val != "") $schema_insert .= " '".addslashes($val)."',"; else $schema_insert .= "NULL,"; } $schema_insert = ereg_replace(",$", "", $schema_insert); $schema_insert .= ");$crlf"; $temp = $temp.$schema_insert ; } return $temp; } function RestoreFromFile($file){ if (false !== ($fp = fopen($file, 'r'))) { $sql_queries = trim(fread($fp, filesize($file))); $this->splitMySqlFile($pieces, $sql_queries); foreach ($pieces as $query) { if(!$this->execute(trim($query))) return false; } return true; } return false; } function RestoreFromContent($content) { $content = trim($content); $this->splitMySqlFile($pieces, $content); foreach ($pieces as $query) { if(!$this->execute(trim($query))) return false; } return true; } function splitMySqlFile(&$ret, $sql) { $sql= trim($sql); $sql=split(';',$sql); $arr=array(); foreach($sql as $sq) { if($sq!=""); $arr[]=$sq; } $ret=$arr; return true; } } $db=new db(); // 生成 word //$map=array('No','Name','Email','Age'); //echo $db->toWord('test',$map,'档案'); // 生成 Excel //$map=array('No','Name','Email','Age'); //echo $db->toExcel('test',$map,'档案'); // 生成 Xml //echo $db->toExtXml('test',0,20); // 生成 Json //echo $db->toExtJson('test',0,20); //备份 //echo $db->Backuptofile('test','backup'); ?>
 

 

整表备份

 

Php代码
  1. $link = mysql_connect(DB_HOST,DB_USER,DB_PASS);  
  2.   
  3. $tables = mysql_list_tables(DB_NAME);  
  4. $cachetables = array(); $tableselected = array();  
  5.   
  6. while ($table = mysql_fetch_row($tables))  
  7. {  
  8.    $cachetables[$table[0]] = $table[0];  
  9.    $tableselected[$table[0]] = 1;  
  10. }  
  11.   
  12. $table = $cachetables;  
  13. $filename =  DB_NAME . "_" . date("Y_m_d_H_i_s") . ".sql";  
  14. $path = "sql/" . $filename;  
  15.   
  16. $filehandle = fopen($path, "w");  
  17.   
  18. $result = mysql_query("SHOW tables");  
  19. while ($currow = mysql_fetch_array($result))  
  20. {  
  21.    if (isset($table[$currow[0]]))  
  22.    {  
  23.      sqldumptable($currow[0], $filehandle);  
  24.      fwrite($filehandle, "\n\n\n");  
  25.    }  
  26. }  
  27.   
  28. fclose($filehandle);  
  29.   
  30.   
  31. $update_data = array('filename' => $filename, 'postdate' => mktime());  
  32. $db->insert('backup_db', $update_data);  
  33.   
  34. // data dump functions  
  35. function sqldumptable($table, $fp = 0)  
  36. {  
  37.     $tabledump = "DROP TABLE IF EXISTS " . $table . ";\n";  
  38.     $result = mysql_fetch_array(mysql_query("SHOW CREATE TABLE " . $table));  
  39.     //echo "SHOW CREATE TABLE $table";  
  40.     $tabledump .= $result[1] . ";\r\n";  
  41.   
  42.     if ($fp) {  
  43.         fwrite($fp, $tabledump);  
  44.     } else {  
  45.         echo $tabledump;  
  46.     }  
  47.     // get data  
  48.     $rows = mysql_query("SELECT * FROM " . $table);  
  49.     // $numfields=$DB->num_fields($rows);  
  50.     $numfields = mysql_num_fields($rows);  
  51.     while ($row = mysql_fetch_array($rows)) {  
  52.         $tabledump = "INSERT INTO " . $table . " VALUES(";  
  53.   
  54.         $fieldcounter = -1;  
  55.         $firstfield = 1;  
  56.         // get each field's data  
  57.         while (++$fieldcounter < $numfields) {  
  58.             if (!$firstfield) {  
  59.                 $tabledump .= ", ";  
  60.             } else {  
  61.                 $firstfield = 0;  
  62.             }  
  63.   
  64.             if (!isset($row[$fieldcounter])) {  
  65.                 $tabledump .= "NULL";  
  66.             } else {  
  67.                 $tabledump .= "'" . mysql_escape_string($row[$fieldcounter]) . "'";  
  68.             }  
  69.         }  
  70.   
  71.         $tabledump .= ");\n";  
  72.   
  73.         if ($fp) {  
  74.             fwrite($fp, $tabledump);  
  75.         } else {  
  76.             echo $tabledump;  
  77.         }  
  78.     }  
  79.     mysql_free_result($rows);  
  80. }  
$link = mysql_connect(DB_HOST,DB_USER,DB_PASS); $tables = mysql_list_tables(DB_NAME); $cachetables = array(); $tableselected = array(); while ($table = mysql_fetch_row($tables)) { $cachetables[$table[0]] = $table[0]; $tableselected[$table[0]] = 1; } $table = $cachetables; $filename = DB_NAME . "_" . date("Y_m_d_H_i_s") . ".sql"; $path = "sql/" . $filename; $filehandle = fopen($path, "w"); $result = mysql_query("SHOW tables"); while ($currow = mysql_fetch_array($result)) { if (isset($table[$currow[0]])) { sqldumptable($currow[0], $filehandle); fwrite($filehandle, "\n\n\n"); } } fclose($filehandle); $update_data = array('filename' => $filename, 'postdate' => mktime()); $db->insert('backup_db', $update_data); // data dump functions function sqldumptable($table, $fp = 0) { $tabledump = "DROP TABLE IF EXISTS " . $table . ";\n"; $result = mysql_fetch_array(mysql_query("SHOW CREATE TABLE " . $table)); //echo "SHOW CREATE TABLE $table"; $tabledump .= $result[1] . ";\r\n"; if ($fp) { fwrite($fp, $tabledump); } else { echo $tabledump; } // get data $rows = mysql_query("SELECT * FROM " . $table); // $numfields=$DB->num_fields($rows); $numfields = mysql_num_fields($rows); while ($row = mysql_fetch_array($rows)) { $tabledump = "INSERT INTO " . $table . " VALUES("; $fieldcounter = -1; $firstfield = 1; // get each field's data while (++$fieldcounter < $numfields) { if (!$firstfield) { $tabledump .= ", "; } else { $firstfield = 0; } if (!isset($row[$fieldcounter])) { $tabledump .= "NULL"; } else { $tabledump .= "'" . mysql_escape_string($row[$fieldcounter]) . "'"; } } $tabledump .= ");\n"; if ($fp) { fwrite($fp, $tabledump); } else { echo $tabledump; } } mysql_free_result($rows); }
 

导入数据库

 

Php代码
  1. <?php  
  2.   
  3.   
  4.     $file_dir = dirname(__FILE__);  
  5.     $file_name = "2010-05-09-bak.sql";  
  6.   
  7.     $conn = mysql_connect(DB_HOST,DB_USER,DB_PASS);  
  8.     mysql_select_db(DB_NAME, $conn);  
  9.   
  10.       
  11.     $get_sql_data = file_get_contents($file_name, $file_dir);  
  12.   
  13.       
  14.   
  15.     $explode = explode(";", $get_sql_data);  
  16.     $cnt = count($explode);  
  17.     for ($i=0; $i<$cnt; $i++)   
  18.     {  
  19.         $sql = $explode[$i];  
  20.         $result = mysql_query($sql);  
  21.         mysql_query("set names 'utf8'");  
  22.   
  23.         if ($result) {  
  24.             echo "成功:".$i."个查询<br>";  
  25.         } else {  
  26.             echo "导入失败:".mysql_error();  
  27.         }  
  28.     }  
  29. ?> 
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载