继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

php的数据库备份代码

FFIVE
关注TA
已关注
手记 414
粉丝 70
获赞 458

<?php

class backUp{

private    $mysql_link;//链接标识

private    $dbName;    //数据库名

private    $dataDir;     //数据所要存放的目录

private    $tableNames;//表名

public function __construct($mysql_link){

$this->mysql_link = $mysql_link;

}

public function backupTables($dbName,$dataDir,$tableNames){          //开始备份

global $pdo;

global $database;

$this->dbName  = $dbName;

$this->dataDir  = $dataDir;

$this->tableNames = $tableNames;

$tables=$this->delarray($this->tableNames);

$sqls='';

foreach($tables as $tablename){

$tablename =$tablename['Tables_in_'.$database];

if($tablename == ''){//表不存在时

continue;

}

//************************以下是形成SQL的前半部分**************

//如果存在表,就先删除

$sqls .= "\nDROP TABLE IF EXISTS $tablename;\n\n";

//读取表结构

try{

$rs = $pdo->query('SHOW CREATE TABLE'.$tablename); //创表语句

}catch(PDOException $e){

var_dump($e);

}

$row=$rs->fetch();

//获得表结构组成SQL

$sqls.=$row['Create Table'].";\n\n";

unset($rs);

unset($row);

//************************以下是形成SQL的后半部分**************

//查寻出表中的所有数据

$rs=$pdo->query("select * from ".$tablename);

$result=$rs->setFetchMode (PDO::FETCH_ASSOC);

$rows=$rs->fetchAll();

$count = $rs->rowCount();

echo '<br>'.$count.'<br>';

$i = 0;

//$sqls.="INSERT INTO $tablename VALUES ";

foreach ($rows as $row) {

//var_dump($row);

$douhao="";

$sqls.="INSERT INTO$tablename VALUES(";

foreach ($row as $ro) {

$ro=addslashes($ro);

$sqls.=$douhao.'('.'\''.$ro.'\''.")";

$douhao=",";

}

$sqls.=");\n";

}

//$sqls.=";\n";

}

$backfilepath=$this->dataDir.$database.date("Y-m-d",time()).'.sql';

//写入文件

$filehandle = fopen($backfilepath, "w");

fwrite($filehandle, $sqls);

fclose($filehandle);

return true;

}

public function delarray($array){   //处理传入进来的数组

global $pdo;

global $database;

$array_del = array('first'=>$array);         //echo '传进函数的'.$array_del['first'];

foreach($array_del as $tables){

if($tables == '*'){    //所有的表(获得表名时不能按常规方式来组成一个数组)

$newtables =$pdo->query('show tables from '.$database);

$tableList = array();

$tableList =$newtables->fetchAll();

}else{

$tableList=$array_del;

break;

}

}

return $tableList;

}

//end

}

global $pdo ;

global $database;

$database = 'test';

$dir='./';

$pdo = newPDO('mysql:host=localhost;dbname='.$database,'root','',

array(PDO::ATTR_PERSISTENT=> true,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

if (!$pdo) {

echo'connect_wrong';

}

$data = new backUp($pdo);

$success =$data->backupTables($database,$dir,'*');

if ($success) {

echo'backup_okay';

}

?>



作者:曾小乱
链接:https://www.jianshu.com/p/9ca991df05b0

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP