欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-08-18 18:27:09
单表备份代码:复制代码 代码如下:
单表备份
代码:
复制代码 代码如下:

<?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)   
      {   

       /*(";  
      foreach($result as $key=>$val)  
      {  
       $schema_insert .= " `".$key."`,";  
      }  
      $schema_insert = ereg_replace(",$", "", $schema_insert);  
      $schema_insert .= ")   
      */ 
      $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');    
?>

整表备份
复制代码 代码如下:

$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
/************
*
php导入.sql文件
运行版本:php5,php4 使用的时候请选择
作者:panxp
邮件:coolpan123@gmail.com
*
*************/
    $file_dir = dirname(__file__);
    $file_name = "2010-05-09-bak.sql";
    $conn = mysql_connect(db_host,db_user,db_pass);
    mysql_select_db(db_name, $conn);
    /** php5 版本 **/
    $get_sql_data = file_get_contents($file_name, $file_dir);
    /** 
    * php4 版本
    if(file_exists($file_dir."/".$file_name))
    {
        $get_sql_data = fopen($file_dir."/".$file_name,"r");  
        if(!$get_sql_data)
        {
            echo "不能打开文件";
        }
        else
        {
            $get_sql_data = fread($get_sql_data, filesize ($file_dir."/".$file_name));
        }
    }
    ***/
    $explode = explode(";", $get_sql_data);
    $cnt = count($explode);
    for ($i=0; $i<$cnt; $i++)
    {
        $sql = $explode[$i];
        $result = mysql_query($sql);
        mysql_query("set names 'utf8'");
        if ($result) {
            echo "成功:".$i."个查询<br>";
        } else {
            echo "导入失败:".mysql_error();
        }
    }
?>