<?php
header('Content-type:text/html; charset=utf-8');
Header("Content-type: application/octet-stream");
header("Content-Disposition:attachment; filename=".date( 'YmdHis ').".sql");
class BakAction extends Action{
/**
*返回?cái)?shù)據(jù)庫(kù)中的數(shù)據(jù)表
*/
protected function getTable(){
$dbName=C('DB_NAME');
$result=M()->query('show tables from '.$dbName);
foreach ($result as $v){
$tbArray[]=$v['Tables_in_'.C('DB_NAME')];
}
return $tbArray;
}
public function index(){
$table=$this->getTable();
$struct=$this->bakStruct($table);
$record=$this->bakRecord($table);
echo $struct;
echo $record;
}
/**
*備份數(shù)據(jù)表結(jié)構(gòu)
*/
protected function bakStruct($array){
foreach ($array as $v){
$tbName=$v;
$result=M()->query('show columns from '.$tbName);
$sql.="--\r\n";
$sql.="-- 數(shù)據(jù)表結(jié)構(gòu): `$tbName`\r\n";
$sql.="--\r\n\r\n";
$sql.="create table `$tbName` (\r\n";
$rsCount=count($result);
foreach ($result as $k=>$v){
$field = $v['Field'];
$type = $v['Type'];
$default= $v['Default'];
$extra = $v['Extra'];
$null = $v['Null'];
if(!($default=='')){
$default='default '.$default;
}
if($null=='NO'){
$null='not null';
}else{
$null="null";
}
if($v['Key']=='PRI'){
$key = 'primary key';
}else{
$key = '';
}
if($k<($rsCount-1)){
$sql.="`$field` $type $null $default $key $extra ,\r\n";
}else{
//最后一條不需要","號(hào)
$sql.="`$field` $type $null $default $key $extra \r\n";
}
}
$sql.=")engine=innodb charset=utf8;\r\n\r\n";
}
return str_replace(')',')',$sql);
}
/**
*備份數(shù)據(jù)表數(shù)據(jù)
*/
protected function bakRecord($array){
foreach ($array as $v){
$tbName=$v;
$rs=M()->query('select * from '.$tbName);
if(count($rs)<=0){
continue;
}
$sql.="--\r\n";
$sql.="-- 數(shù)據(jù)表中的數(shù)據(jù): `$tbName`\r\n";
$sql.="--\r\n\r\n";
foreach ($rs as $k=>$v){
$sql.="INSERT INTO `$tbName` VALUES (";
foreach ($v as $key=>$value){
if($value==''){
$value='null';
}
$type=gettype($value);
if($type=='string'){
$value="'".addslashes($value)."'";
}
$sql.="$value," ;
}
$sql.=");\r\n\r\n";
}
}
return str_replace(')',')',$sql);
}
}
?>
在做FOMS時(shí)需要個(gè)數(shù)據(jù)庫(kù)備份類,但是在thinkphp官網(wǎng)論壇上面好像沒(méi)有這個(gè)東西,隨便弄了個(gè),自我感覺(jué)不是很好,只是能用。
該類需要有thinkphp框架支持。
--------------------------------------分割線----------------------------------------
<?php
protected function bakStruct($array)
{
foreach ($array as $v)
{
$tbName = $v;
//$sql.="DROP TABLE IF EXISTS `$v`;\r\n\r\n";
$result = M()->query('SHOW CREATE TABLE ' . $tbName);
$sql .= $result['0']['Create Table'] . ";\r\n\r\n";
}
return str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $sql);
}
?>
更多信息請(qǐng)查看IT技術(shù)專欄