本篇文章是对php备份数据库代码(生成word,excel,json,xml,sql)进行了详细的分析介绍,需要的朋友参考下
单表备份
复制代码 代码如下:
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
$str.="{";
$count=count($result[$i]);
$j=1;
foreach($result[$i] as $key=>$val)
{
if($j
{
$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="\n";
$xml.="
$xml.="\t
$xml.="\t
for($i=0;$i
$xml.="\t\t
foreach($result[$i] as $key=>$val)
$xml.="\t\t\t".$val."".$key.">\n";
$xml.="\t\t
}
$xml.="\t
$xml.="
return $xml;
}
//输出word表格
function toWord($table,$mapping,$fileName)
{
header('Content-type: application/doc');
header('Content-Disposition: attachment; filename="'.$fileName.'.doc"');
echo '
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="[url=http://www.w3.org/TR/REC-html40][/url]">
'.$val.' | ';
'.$val.' | ';
'.$val.' | ';
'.$val.' | ';
复制代码 代码如下: