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

本文介绍了使用PHP备份数据库到多种格式(Word, Excel, JSON, XML, SQL),包括单表备份、整表备份,以及如何导入SQL文件到数据库。提供了代码示例,覆盖了从备份到恢复的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单表备份

 

代码:

 

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[$ias $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[$ias $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.       foreach($result as $key=>$val) 
  289.       { 
  290.        $schema_insert .= " `".$key."`,"; 
  291.       } 
  292.       $schema_insert = ereg_replace(",$", "", $schema_insert); 
  293.       $schema_insert .= ")  
  294.       */  
  295.       $schema_insert = "INSERT INTO  $table VALUES (";  
  296.       foreach($result as $key=>$val)  
  297.       {  
  298.        if($val != "")  
  299.        $schema_insert .= " '".addslashes($val)."',";  
  300.        else  
  301.        $schema_insert .= "NULL,";  
  302.       }  
  303.       $schema_insert = ereg_replace(",$"""$schema_insert);  
  304.       $schema_insert .= ");$crlf";  
  305.       $temp = $temp.$schema_insert ;  
  306.       }  
  307.       return $temp;  
  308.     }  
  309.   
  310.     function RestoreFromFile($file){  
  311.       if (false !== ($fp = fopen($file'r'))) {  
  312.        $sql_queries = trim(fread($fpfilesize($file)));  
  313.        $this->splitMySqlFile($pieces$sql_queries);  
  314.        foreach ($pieces as $query) {  
  315.         if(!$this->execute(trim($query)))  
  316.         return false;  
  317.        }  
  318.        return true;  
  319.       }  
  320.       return false;  
  321.     }  
  322.   
  323.     function RestoreFromContent($content)  
  324.     {  
  325.       $content = trim($content);  
  326.       $this->splitMySqlFile($pieces$content);  
  327.       foreach ($pieces as $query) {  
  328.        if(!$this->execute(trim($query)))  
  329.        return false;  
  330.       }  
  331.       return true;  
  332.     }  
  333.   
  334.     function splitMySqlFile(&$ret$sql)  
  335.     {  
  336.       $sql= trim($sql);  
  337.       $sql=split(';',$sql);  
  338.       $arr=array();  
  339.       foreach($sql as $sq)  
  340.       {  
  341.         if($sq!="");  
  342.         $arr[]=$sq;  
  343.       }  
  344.       $ret=$arr;  
  345.       return true;  
  346.     }  
  347. }  
  348.   
  349.   
  350. $db=new db();  
  351.   
  352. // 生成 word   
  353. //$map=array('No','Name','Email','Age');  
  354. //echo  $db->toWord('test',$map,'档案');  
  355.   
  356. // 生成 Excel   
  357. //$map=array('No','Name','Email','Age');  
  358. //echo  $db->toExcel('test',$map,'档案');  
  359.   
  360. // 生成 Xml   
  361. //echo  $db->toExtXml('test',0,20);  
  362.   
  363. // 生成 Json   
  364. //echo  $db->toExtJson('test',0,20);  
  365.   
  366. //备份      
  367. //echo $db->Backuptofile('test','backup');  
  368.   
  369.   
  370. ?>  
 

 

整表备份

 

Php代码   收藏代码
  1. <?  
  2. backup_tables('localhost','root','root','test');  
  3.   
  4.   
  5. /* backup the db OR just a table */  
  6. function backup_tables($host,$user,$pass,$name,$tables = '*')  
  7. {  
  8.     
  9.   $link = mysql_connect($host,$user,$pass);  
  10.   mysql_select_db($name,$link);  
  11.     
  12.   //get all of the tables  
  13.   if($tables == '*')  
  14.   {  
  15.     $tables = array();  
  16.     $result = mysql_query('SHOW TABLES');  
  17.     while($row = mysql_fetch_row($result)) $tables[] = $row[0];  
  18.   }  
  19.   else $tables = is_array($tables) ? $tables : explode(',',$tables);  
  20.     
  21.   //cycle through  
  22.   foreach($tables as $table)  
  23.   {  
  24.     $result = mysql_query('SELECT * FROM '.$table);  
  25.     $num_fields = mysql_num_fields($result);  
  26.       
  27.     $return.= 'DROP TABLE '.$table.';';  
  28.     $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));  
  29.     $return.= "\n\n".$row2[1].";\n\n";  
  30.       
  31.     for ($i = 0; $i < $num_fields$i++)   
  32.     {  
  33.       while($row = mysql_fetch_row($result))  
  34.       {  
  35.         $return.= 'INSERT INTO '.$table.' VALUES(';  
  36.         for($j=0; $j<$num_fields$j++)   
  37.         {  
  38.           $row[$j] = addslashes($row[$j]);  
  39.           $row[$j] = ereg_replace("\n","\\n",$row[$j]);  
  40.           if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }  
  41.           if ($j<($num_fields-1)) { $return.= ','; }  
  42.         }  
  43.         $return.= ");\n";  
  44.       }  
  45.     }  
  46.     $return.="\n\n\n";  
  47.   }  
  48.     
  49.   //save file  
  50.   $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');  
  51.   fwrite($handle,$return);  
  52.   fclose($handle);  
  53. }  
  54.   
  55. ?>  

 

 

或者:

 

 

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. }  
 

导入数据库

 

Php代码   收藏代码
  1. <?php  
  2. /************ 
  3. * 
  4. PHP导入.sql文件 
  5. 运行版本:php5,php4 使用的时候请选择 
  6. 作者:panxp 
  7. 邮件:coolpan123@gmail.com 
  8. * 
  9. *************/  
  10.   
  11.     $file_dir = dirname(__FILE__);  
  12.     $file_name = "2010-05-09-bak.sql";  
  13.   
  14.     $conn = mysql_connect(DB_HOST,DB_USER,DB_PASS);  
  15.     mysql_select_db(DB_NAME, $conn);  
  16.   
  17.     /** PHP5 版本 **/  
  18.     $get_sql_data = file_get_contents($file_name$file_dir);  
  19.   
  20.     /**   
  21.     * PHP4 版本 
  22.     if(file_exists($file_dir."/".$file_name))  
  23.     { 
  24.         $get_sql_data = fopen($file_dir."/".$file_name,"r");    
  25.         if(!$get_sql_data)  
  26.         { 
  27.             echo "不能打开文件"; 
  28.         }  
  29.         else  
  30.         { 
  31.             $get_sql_data = fread($get_sql_data, filesize ($file_dir."/".$file_name)); 
  32.         } 
  33.     } 
  34.     ***/  
  35.   
  36.     $explode = explode(";"$get_sql_data);  
  37.     $cnt = count($explode);  
  38.     for ($i=0; $i<$cnt$i++)   
  39.     {  
  40.         $sql = $explode[$i];  
  41.         $result = mysql_query($sql);  
  42.         mysql_query("set names 'utf8'");  
  43.   
  44.         if ($result) {  
  45.             echo "成功:".$i."个查询<br>";  
  46.         } else {  
  47.             echo "导入失败:".mysql_error();  
  48.         }  
  49.     }  
  50. ?>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值