php實(shí)例分享之mysql數(shù)據(jù)備份
備份:表結(jié)構(gòu)和數(shù)據(jù)完全分開,默認(rèn)有一個(gè)文件會(huì)記錄所有表的結(jié)構(gòu),然后表中數(shù)據(jù)的備份 如果超過(guò)分卷的大小則會(huì)分成多個(gè)文件,不然則一個(gè)文件,參考了別人的代碼,不過(guò)寫的嘛,差強(qiáng) 人意,以后慢慢改吧。。。
代碼如下:
<?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';
//構(gòu)造方法 鏈接數(shù)據(jù)庫(kù)
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("數(shù)據(jù)庫(kù)系統(tǒng)連接失?。?);
mysql_query("set names ".$charset, $this->conn);
mysql_select_db($dbName, $this->conn) or die("數(shù)據(jù)庫(kù)連接失?。?);
$this->host = $host;
$this->dbName = $dbName;
}
//獲取數(shù)據(jù)庫(kù)所有表名
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;
}
//獲取數(shù)據(jù)庫(kù)表的字段信息
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;
}
//獲取表中的數(shù)據(jù)
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;
}
//備份數(shù)據(jù)庫(kù)
public function getBackUpDataByTable ($tables, $path='', $fileName = 'seocheck', $subsection = '2') {
if(empty($tables)) $this->_showMsg('未能指定要備份的表!!!', true);
$page = 0;//卷數(shù)
$path = empty($path) ? $_SERVER['DOCUMENT_ROOT'].'/core/Runtime/Data/'.$fileName.'Demo/' : $path;
if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$mysql_info = $this->_retrieve();
$fieldsByTable = array();
if(is_array($tables)) {
$this->_showMsg('開始備份,數(shù)據(jù)正在初始化中,請(qǐng)勿關(guān)閉瀏覽器...');
$fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $mysql_info, $method="ab+");
if($fw !== false) {
$this->_showMsg('備份數(shù)據(jù)庫(kù)基本信息成功。。。');
}
foreach ($tables as $table) {
$tableInfo = $this->getFieldsByTable($table);
if(!empty($tableInfo)) {
$this->_showMsg('獲取表['.$table.']結(jié)構(gòu)成功。。。');
$fw = $this->writeFileByBackUpData($path.$this->dbName.'_table.sql', $tableInfo[$table], $method="ab+");
if($fw === false) {
$this->_showMsg('備份表['.$table.']結(jié)構(gòu)失敗。。。', true);
} else {
$this->_showMsg('備份表['.$table.']結(jié)構(gòu)成功,開始獲取數(shù)據(jù)。。。');
};
} else {
$this->_showMsg('獲取數(shù)據(jù)庫(kù)['.$this->dbName.']表結(jié)構(gòu)失敗,請(qǐng)稍后再試!。。。', true);
}
$this->_insertSqlByTableForAll($path, $table, $subsection);
}
} else {
$this->_showMsg('開始備份,數(shù)據(jù)正在初始化中,請(qǐng)勿關(guān)閉瀏覽器...');
$tableInfo = $this->getFieldsByTable($tables);
if(!empty($tableInfo)) {
$this->_showMsg('獲取表['.$tables.']結(jié)構(gòu)成功。。。');
$fw = $this->writeFileByBackUpData($path.$this->dbName.'_'.$tables.'_table.sql', $mysql_info.$tableInfo[$tables]);
if($fw === false) {
$this->_showMsg('備份表['.$tables.']結(jié)構(gòu)失敗。。。', true);
} else {
$this->_showMsg('備份表['.$tables.']結(jié)構(gòu)成功,開始獲取數(shù)據(jù)。。。');
}
} else {
$this->_showMsg('獲取表['.$tables.']結(jié)構(gòu)失敗,請(qǐng)稍后再試!。。。', true);
}
$res = $this->_insertSqlByTableForAll($path, $tables, $subsection);
}
}
//數(shù)據(jù)庫(kù)基本信息
private function _retrieve() {
$backUp = '';
$backUp .= '--' . "\n";
$backUp .= '-- MySQL database dump' . "\n";
$backUp .= '-- Created by DbBackUp class, Power By chujiu. ' . "\n";
$backUp .= '--' . "\n";
$backUp .= '-- 主機(jī): ' . $this->host . "\n";
$backUp .= '-- 生成日期: ' . date ( 'Y' ) . ' 年 ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . "\n";
$backUp .= '-- MySQL版本: ' . mysql_get_server_info () . "\n";
$backUp .= '-- PHP 版本: ' . phpversion () . "\n";
$backUp .= "\n\n";
$backUp .= "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';\n";
$backUp .= "SET time_zone = '+00:00';\n\n";
$backUp .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n";
$backUp .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n";
$backUp .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n";
$backUp .= "/*!40101 SET NAMES utf8*/;\n\n";
$backUp .= "--\n-- Database: `{$this->dbName}`\n--\n\n-- --------------------------------------------------------\n\n";
return $backUp;
}
/**
* 插入單條記錄
*
* @param string $row
*/
private function _insertSql($row, $table) {
// sql字段逗號(hào)分割
$insert = '';
$insert .= "INSERT INTO `" . $table . "` VALUES(";
foreach($row as $key=>$val) {
$insert .= "'".$val."',";
}
$insert = substr($insert, 0 ,-1);
$insert .= ");" . "\n";
return $insert;
}
/**
* 生成一個(gè)表的inser語(yǔ)句
* @param string $table
* @param string $subsection 分卷大小
*/
private function _insertSqlByTableForAll($path, $table, $subsection) {
$i = 0;
$insertSqlByTable = '';
$res = mysql_query("SELECT * FROM `{$table}`", $this->conn);
if(!$res) die('MySQL Error: ' . mysql_error());
while($rows = mysql_fetch_assoc($res)) {
$insertSqlByTable .= $this->_insertSql($rows, $table);
$size = strlen($insertSqlByTable);
if($size > $subsection*1024*1024) {
$fw = $this->writeFileByBackUpData($path.$table.$i.$this->tag.'.sql', $insertSqlByTable);
if($fw === false) $this->_showMsg('數(shù)據(jù)庫(kù)表['.$table.'],卷 '.$i.' 寫入文件失敗,請(qǐng)稍后再試?。。?,true);
$this->_showMsg('數(shù)據(jù)庫(kù)表['.$table.'],卷 '.$i.' 備份成功!備份文件:[ '.$path.$table.$i.$this->tag.'.sql ]');
$insertSqlByTable = '';
$i+=1;
}
}
// insertSqlByTable大小不夠分卷大小
if ($insertSqlByTable != "") {
$fw = $this->writeFileByBackUpData($path.$table.$this->tag.'.sql', $insertSqlByTable);
if($fw === false) $this->_showMsg('數(shù)據(jù)庫(kù)表['.$table.']寫入文件失敗,請(qǐng)稍后再試!?。浞菸募?[ '.$path.$table.$this->tag.'.sql ]',true);
$this->_showMsg('數(shù)據(jù)庫(kù)表['.$table.'] 備份成功!備份文件:[ '.$path.$table.$this->tag.'.sql ]');
}
$this->_showMsg('數(shù)據(jù)庫(kù)表['.$table.']全部備份成功!');
}
// 寫入文件
public function writeFileByBackUpData($fileName, $data, $method="rb+", $iflock=1, $check=1, $chmod=1){
$check && @strpos($fileName, '..')!==false && exit('Forbidden');
@touch($fileName);
$handle = @fopen($fileName, $method);
if($iflock) {
@flock($handle,LOCK_EX);
}
$fw = @fwrite($handle,$data);
if($method == "rb+") ftruncate($handle, strlen($data));
fclose($handle);
$chmod && @chmod($fileName,0777);
return $fw;
}
/**
* path: 生成壓縮包的路徑
* fileName : 要壓縮的文件名 通常和path 同一目錄
*/
public function createZipByBackUpFile($path) {
$db_base_files = $this->getFileByBackUpDir($path);
if(!empty($db_base_files)) {
$zip = new ZipArchive;
if($zip->open($path.$this->dbName.date('Ymd').'.zip', ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
die ("cannot open".$this->dbName.date('Ymd')."zip for writing.");
foreach ($db_base_files as $key => $value) {
if(is_file($value)) {
$file_name = basename($value);
$info[] = $zip->addFile($value, $file_name);// 避免壓縮包里有文件的路徑
}
}
$zip->close();
if(file_exists($path.$this->dbName.date('Ymd').'.zip'))
foreach ($db_base_files as $val) {
unlink($val);
}
if(count(array_filter($info)) > 0) return true;
}
return false;
}
//獲取文件
public function getFileByBackUpDir($path) {
$info = array();
$db_base_files = array();
if( @file_exists($path) && is_dir($path) ) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if($file != '.' && $file != '..') {
if( strripos($file, 'seocheck') !== false ) {
$db_base_files[] = $path.$file;
}
}
}
closedir($dh);
}
}
return $db_base_files;
}
/**
* @path: 生成壓縮包的路徑
* @fileName : 要解壓的文件名 默認(rèn)解壓到path 目錄
*/
public function uncompressZip($path, $zipName) {
$path = empty($path) ? $_SERVER['DOCUMENT_ROOT'].'/core/Runtime/Data/' : $path;
$zip = new ZipArchive;
if ($zip->open($path.$zipName) === TRUE) {
$zip->extractTo($path);
$zip->close();
return true;
} else {
return false;
}
}
//導(dǎo)入數(shù)據(jù)庫(kù)
public function importingDataBySqlFile () {
}
// 及時(shí)輸出信息
private function _showMsg($msg,$err=false){
if($err === true) {
echo "<p style='font-size:14px;'><span style='color:red;'>ERROR: --- " . $msg . "</span></p>";exit;
}
echo "<p style='font-size:14px;'><span style='color:green;'>OK: --- " . $msg . "</span></p>";
}
// 鎖定數(shù)據(jù)庫(kù),以免備份或?qū)霑r(shí)出錯(cuò)
private function lock($table, $op = "WRITE") {
if (mysql_query ( "lock tables " . $table . " " . $op ))
return true;
else
return false;
}
// 解鎖
private function unlock() {
if (mysql_query ( "unlock tables" ))
return true;
else
return false;
}
// 析構(gòu)
public function __destruct() {
if($this->conn){
mysql_query ( "unlock tables", $this->conn );
mysql_close ( $this->conn );
}
}
}
?>
- php實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)備份與還原類實(shí)例
- 使用PHP備份MYSQL數(shù)據(jù)的多種方法
- 使用PHP備份MySQL和網(wǎng)站發(fā)送到郵箱實(shí)例代碼
- 詳解MYSQL的備份還原(PHP實(shí)現(xiàn))
- PHP備份/還原MySQL數(shù)據(jù)庫(kù)的代碼
- 備份mysql數(shù)據(jù)庫(kù)的php代碼(一個(gè)表一個(gè)文件)
- php MYSQL 數(shù)據(jù)備份類
- PHP XML備份Mysql數(shù)據(jù)庫(kù)
- php實(shí)現(xiàn)mysql數(shù)據(jù)庫(kù)備份類
- 用PHP實(shí)現(xiàn)XML備份Mysql數(shù)據(jù)庫(kù)
- php實(shí)現(xiàn)mysql備份恢復(fù)分卷處理的方法
相關(guān)文章
php將服務(wù)端的文件讀出來(lái)顯示在web頁(yè)面實(shí)例
本篇文章主要介紹了php將服務(wù)端的文件讀出來(lái)顯示在web頁(yè)面實(shí)例,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2016-10-10深入解析Laravel5.5中的包自動(dòng)發(fā)現(xiàn)Package Auto Discovery
眾所周知Laravel 5.5 發(fā)布在即,目前已經(jīng)確定會(huì)增加一個(gè)神奇的新特性:Package Auto Discovery。下面這篇文章主要給大家深入的介紹了關(guān)于Laravel5.5中包自動(dòng)發(fā)現(xiàn)Package Auto Discovery的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-09-09Laravel中獲取路由參數(shù)Route Parameters的五種方法示例
這篇文章主要給大家介紹了關(guān)于Laravel中獲取路由參數(shù)Route Parameters的五種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Laravel具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-09-09PHP實(shí)現(xiàn)長(zhǎng)文章分頁(yè)實(shí)例代碼(附源碼)
當(dāng)文章內(nèi)容比較長(zhǎng),為了更好的滿足用戶體驗(yàn)度,我們將文章內(nèi)容分頁(yè)顯示處理,而一般分頁(yè)處理是在后臺(tái)發(fā)布文章的時(shí)候就將提交的內(nèi)容生成多個(gè)分頁(yè)后的靜態(tài)文件。通過(guò)本文結(jié)合實(shí)例采用php動(dòng)態(tài)將長(zhǎng)文章內(nèi)容進(jìn)行分頁(yè)處理2016-02-02PHP和javascript常用正則表達(dá)式及用法實(shí)例
這篇文章主要介紹了常用的PHP和javascript正則表達(dá)式及用法實(shí)例,精心收集的PHP和javascript正則表達(dá)式各10個(gè),需要的朋友可以參考下2014-07-07PHP register_shutdown_function函數(shù)的深入解析
本篇文章是對(duì)PHP register_shutdown_function函數(shù)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06Laravel學(xué)習(xí)教程之request validation的編寫
這篇文章主要給大家介紹了關(guān)于Laravel學(xué)習(xí)教程之request validation編寫的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10解決phpcms更換javascript的幻燈片代碼調(diào)用圖片問(wèn)題
這篇文章主要介紹了解決phpcms更換javascript的幻燈片代碼調(diào)用圖片問(wèn)題,需要的朋友可以參考下2014-12-12