php版mysql数据库备份类baker.class.php [不完整]
说明:
一个备份MySQL数据库到SQL文件的php类。
不足:
此类没有错误提示功能,不可直接用生“生产”。这也是本文题目中添加“ [不完整]”的原因;
此类也不会自己创建目录,使用前请确认存放备份文件的目录可写;
其它未知错误。
代码:
<?php
class baker{
/**
* 说明:mysql备份类
* 作者:upall,http://upall.cn/
* 日期:22:45 2011年5月26日 星期四
* 用法:
* 备份数据库中的所有表:
* new baker('localhost:3306','root','','mysql',array('*'),'./data/','DB','utf8');
* 备份数据库中的一个表:
* new baker('localhost:3306','root','','mysql',array('user'),'./data/','DB','utf8');
* 备份数据库中的多个表:
* new baker('localhost:3306','root','','mysql',array('user','log','access'),'./data/','DB','utf8');
* 以root身份使用空密码备份mysql数据库所有表:
* new backer();
* 警告:
* 0.使用者使用此代码的全部或者部分所产生的一切后果由使用者承担;
* 1.此baker类没有错误提示及判断功能;
* 2.本人不提供技术支持;
* 3.升级后的代码请自行关注http://upall.cn/。
*/
public $host = 'localhost:3306';
public $user = 'root';
public $pwd = '';
public $db = 'mysql';
public $charset = 'utf8'; // MySQL中不是“UTF-8”!!!!
public $dataDir = './'; // 末尾加“/”
public $fileName = 'DBBAK';
public $tableArray = array('*');
public $link;
public function __construct(
$host = '',
$user = '',
$pwd = '',
$db = '',
$tableArray = '',
$dataDir = '',
$fileName = '',
$charset = ''
){
!empty($host) ? $this->host = $host : '';
!empty($user) ? $this->user = $user : '';
!empty($pwd) ? $this->pwd = $pwd : '';
!empty($db) ? $this->db = $db : '';
!empty($tableArray) ? $this->tableArray = $tableArray : '';
!empty($dataDir) ? $this->dataDir = $dataDir : '';
!empty($fileName) ? $this->fileName = $fileName : '';
!empty($charset) ? $this->charset = $charset : '';
$this->connect();
$this->bak();
}
public function connect(){
$this->link = @mysql_connect($this->host,$this->user,$this->pwd);
if ($this->link) {
@mysql_select_db($this->db, $this->link);
@mysql_query("SET NAMES '$this->charset'");
}
}
public function bak(){
$tables=$this->delarray($this->tableArray);
$sqls='';
foreach($tables as $tablename){
if($tablename==''){
continue;
}
$sqls .= "DROP TABLE IF EXISTS $tablename;\n";
$rs = @mysql_query("SHOW CREATE TABLE $tablename",$this->link);
$row=mysql_fetch_row($rs);
$sqls.=$row['1'].";\n\n";
unset($rs);
unset($row);
$rs=mysql_query("SELECT * FROM $tablename",$this->link);
$field=mysql_num_fields($rs);
while($rows=mysql_fetch_row($rs)){
$comma='';
$sqls.="INSERT INTO `$tablename` VALUES(";
for($i=0;$i<$field;$i++){
$sqls.=$comma."'".$rows[$i]."'";
$comma=',';
}
$sqls.=");\n\n\n";
}
}
$backfilepath=$this->dataDir.$this->fileName.date("YmdHis",time()).'.sql';
$filehandle = fopen($backfilepath, "w");
fwrite($filehandle, $sqls);
fclose($filehandle);
}
private function delarray($array){
foreach($array as $tables){
if($tables=='*'){
$newtables=mysql_list_tables($this->db);
$tableList = array();
for ($i = 0; $i < mysql_numrows($newtables); $i++){
array_push($tableList,mysql_tablename($newtables, $i));
}
$tableList=$tableList;
}else{
$tableList=$array;
break;
}
}
return $tableList;
}
}
?>
<完。核心代码摘自:http://www.jb51.net/article/18664.htm>