<?php
/*
* Created on 2014
* Link for 527891885@qq.com
* This is seocheck backup class
*/
class DbBackUp {
private $conn;
private $dbName;
private $host;
private $tag = '_b';
//构造方法 链接数据库
public function __construct($host='localhost', $dbUser='root', $dbPwd='', $dbName="seocheck", $charset='utf8') {
@ob_start();
@set_time_limit(0);
$this->conn = mysql_connect($host, $dbUser, $dbPwd, true);
if(!$this->conn) die("数据库系统连接失败!");
mysql_query("set names ".$charset, $this->conn);
mysql_select_db($dbName, $this->conn) or die("数据库连接失败!");
$this->host = $host;
$this->dbName = $dbName;
}
//获取数据库所有表名
public function getTableNames () {
$tables = array();
$result = mysql_list_tables($this->dbName, $this->conn);
if(!$result) die('MySQL Error: ' . mysql_error());
while($row = mysql_fetch_row($result)) {
$tables[] = $row[0];
}
return $tables;
}
//获取数据库表的字段信息
public function getFieldsByTable ($table) {
$fields = array();
$str = '';
$res = mysql_query("SHOW CREATE TABLE `{$table}`", $this->conn);
if(!$res) die('MySQL Error: ' . mysql_error());
while($rows = mysql_fetch_assoc($res)) {
$str = str_replace("CREATE TABLE `{$table}` (", "", $rows['Create Table']);//DROP TABLE IF EXISTS `{$table}`\n
$str = "--\n-- Table structure for table `{$table}`\n--\n\nCREATE TABLE IF NOT EXISTS `{$table}` ( ".$str;
$str = str_replace(",", ", ", $str);
$str = str_replace("`) ) ENGINE=InnoDB ", "`)\n ) ENGINE=InnoDB ", $str);
$str .=";\n\n";
//$str = $str.";\n\n--\n-- Dumping data for table `{$table}`\n--\n\n";
$fields[$rows['Table']] = $str;
}
return $fields;
}
//获取表中的数据
public function getDataByTable($table) {
$data = array();
$str = '';
$res = mysql_query("SELECT * FROM `{$table}`", $this->conn);
if(!$res) die('MySQL Error: ' . mysql_error());
while($rows = mysql_fetch_assoc($res)) {
if(!empty($rows)) {
$data[] = $rows;
}
}
$keys = array_keys($data[0]);
foreach ($keys as $k=>$v) {
$keys[$k] = '`'.$v.'`';
}
$key = join(', ', $keys);
$str = "INSERT INTO `{$table}` ({$key}) VALUES\n";
foreach ($data as $k=>$v) {
$str.="(";
while (list($key, $val) = each($v)) {
if(!is_numeric($val)) {
$str.= "'".$val."', ";
} else {
$str.= $val.', ';
}
}
$str = substr($str, 0, -2);// 后边有空格 所以从-2 开始截取
if($k+1 == count($data)) {
$str.=");\n\n-- --------------------------------------------------------\n\n";
} else {
$str.="),\n";
}
}
return $str;
}