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


Posted in PHP onJune 23, 2013

单表备份
代码:

<?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();
        }
    }
?>

PHP 相关文章推荐
php 数组的创建、调用和更新实现代码
Mar 09 PHP
PHP教程之PHP中shell脚本的使用方法分享
Feb 23 PHP
简单实现限定phpmyadmin访问ip的方法
Mar 05 PHP
CURL状态码列表(详细)
Jun 27 PHP
smarty模板局部缓存方法使用示例
Jun 17 PHP
php foreach正序倒序输出示例代码
Jul 01 PHP
php实现根据IP地址获取其所在省市的方法
Apr 30 PHP
php需登录的文件上传管理系统
Mar 21 PHP
PHP通过微信跳转的Code参数获取用户的openid(关键代码)
Jul 06 PHP
yii通过小物件生成view的方法
Oct 08 PHP
PHP反射原理与用法深入分析
Sep 28 PHP
php高性能日志系统 seaslog 的安装与使用方法分析
Feb 29 PHP
PHP获取MSN好友列表类的实现代码
Jun 23 #PHP
使用php统计字符串中中英文字符的个数
Jun 23 #PHP
php 获取本地IP代码
Jun 23 #PHP
解析PHP提交后跳转
Jun 23 #PHP
解析PHP获取当前网址及域名的实现代码
Jun 23 #PHP
解析MySql与Java的时间类型
Jun 22 #PHP
解析mysql 表中的碎片产生原因以及清理
Jun 22 #PHP
You might like
用PHP的超级变量$_GET获取HTML表单(Form) 数据
2011/05/07 PHP
PHP采集腾讯微博的实现代码
2012/01/19 PHP
解析php dirname()与__FILE__常量的应用
2013/06/24 PHP
PHP图片裁剪函数(保持图像不变形)
2014/05/04 PHP
cakephp打印sql语句的方法
2015/02/13 PHP
PHP实现计算器小功能
2020/08/28 PHP
Javascript 闭包引起的IE内存泄露分析
2012/05/23 Javascript
html文件中jquery与velocity变量中的$冲突的解决方法
2013/11/01 Javascript
js获取json元素数量的方法
2015/01/27 Javascript
原生JavaScript编写俄罗斯方块
2015/03/30 Javascript
Jquery Mobile 自定义按钮图标
2015/11/18 Javascript
基于JavaScript实现网页倒计时自动跳转代码
2015/12/28 Javascript
基于NodeJS+MongoDB+AngularJS+Bootstrap开发书店案例分析
2017/01/12 NodeJs
JS判断键盘是否按的回车键并触发指定按钮点击操作的方法
2017/02/13 Javascript
angularjs实现的购物金额计算工具示例
2018/05/08 Javascript
浅谈bootstrap layer.open中end的使用方法
2019/09/12 Javascript
vue中 v-for循环的用法详解
2020/02/19 Javascript
微信小程序scroll-view的滚动条设置实现
2020/03/02 Javascript
JavaScript 中的执行上下文和执行栈实例讲解
2021/02/25 Javascript
[56:46]2018DOTA2亚洲邀请赛 3.31 小组赛 B组 VP vs Effect
2018/04/01 DOTA
用Python编程实现语音控制电脑
2014/04/01 Python
Python3.x中自定义比较函数
2015/04/24 Python
利用信号如何监控Django模型对象字段值的变化详解
2017/11/27 Python
python学习之matplotlib绘制散点图实例
2017/12/09 Python
用python实现百度翻译的示例代码
2018/03/09 Python
Python读取Word(.docx)正文信息的方法
2018/03/15 Python
Sanic框架异常处理与中间件操作实例分析
2018/07/16 Python
对Python Class之间函数的调用关系详解
2019/01/23 Python
python实现截取屏幕保存文件,删除N天前截图的例子
2019/08/27 Python
CSS中越界问题的经典解决方案【推荐】
2016/04/19 HTML / CSS
在weblogic中发布ejb需涉及到哪些配置文件
2012/01/17 面试题
个人思想理论学习的自我鉴定
2013/11/30 职场文书
中专生自我鉴定书范文
2013/12/28 职场文书
开天辟地观后感
2015/06/09 职场文书
学雷锋广播稿大全
2015/08/19 职场文书
2019年“红色之旅”心得体会1000字(3篇)
2019/09/27 职场文书