PHP instance sharing MySQL data backup _php tutorial

Source: Internet
Author: User
Tags ziparchive import database
Backup: The table structure and data are completely separated, the default one file will record all the structure of the table, and then the data in the table backup if the size of the volume will be divided into multiple files, or a file, referring to someone else's code, but write it, passable, slowly change it later ...

The code is as follows:

Copy the Code code as follows:
/*
* Created on 2014
* Link for 527891885@qq.com
* This is Seocheck backup class
*/
Class DbBackUp {
Private $conn;
Private $dbName;
Private $host;
Private $tag = ' _b ';
Construct Method Link Database
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 ("Database system Connection Failed! ");
mysql_query ("Set names". $charset, $this->conn);
mysql_select_db ($dbName, $this->conn) or Die ("Database connection failed! ");
$this->host = $host;
$this->dbname = $dbName;
}

//Get database All table name
Public Function Gettablenames () {
$tables = array ();
$result = Mysql_list_tables ($this->db Name, $this->conn);
if (! $result) die (' MySQL Error: '. mysql_error ());
while ($row = Mysql_fetch_row ($result)) {
$tables [] = $row [0];
}
return $tables;
}

//Get field information for a database table
Public Function getfieldsbytable ($table) {
$fields = array ();
$str = ";
$res = Mysql_q Uery ("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";
//$str = $str. "; n\n--\n--dumping data for table ' {$table} ' \n--\n\n ';
$fields [$rows [' Table ']] = $STR;
}
return $fields;
}

Get data from a table
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);//There is a space behind it so start with 2 intercept
if ($k +1 = = count ($data)) {
$str. = "); \ n \ nyou----------------------------------------------------------";
} else {
$str. = "), \ n";
}
}
return $str;
}

Backing Up the database
Public Function getbackupdatabytable ($tables, $path = ", $fileName = ' Seocheck ', $subsection = ' 2 ') {
if (empty ($tables)) $this->_showmsg (' failed to specify the table to be backed up!!! ', true);
$page = number of 0;//volumes
$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 (' Start Backup, data initializing, do not close browser ... ');
$FW = $this->writefilebybackupdata ($path. $this->dbname. ' _table.sql ', $mysql _info, $method = "ab+");
if ($FW!== false) {
$this->_showmsg (' Backup database basic information succeeded ... ');
}
foreach ($tables as $table) {
$tableInfo = $this->getfieldsbytable ($table);
if (!empty ($tableInfo)) {
$this->_showmsg (' Get table ['. $table. '] Structural success ... ');
$FW = $this->writefilebybackupdata ($path. $this->dbname. ' _table.sql ', $tableInfo [$table], $method = "ab+");
if ($FW = = = False) {
$this->_showmsg (' Backup table ['. $table. '] Structure failed ... ', true);
} else {
$this->_showmsg (' Backup table ['. $table. '] Structure successful, start getting data ... ');
};
} else {
$this->_showmsg (' Get Database ['. $this->dbname. '] Table structure failed, please try again later .... ', true);
}
$this->_insertsqlbytableforall ($path, $table, $subsection);
}
} else {
$this->_showmsg (' Start Backup, data initializing, do not close browser ... ');
$tableInfo = $this->getfieldsbytable ($tables);
if (!empty ($tableInfo)) {
$this->_showmsg (' Get table ['. $tables. '] Structural success ... ');
$FW = $this->writefilebybackupdata ($path. $this->dbname. ' _ '. $tables. ' _table.sql ', $mysql _info. $tableInfo [$tables]);
if ($FW = = = False) {
$this->_showmsg (' Backup table ['. $tables. '] Structure failed ... ', true);
} else {
$this->_showmsg (' Backup table ['. $tables. '] Structure successful, start getting data ... ');
}
} else {
$this->_showmsg (' Get table ['. $tables. '] Structure failed, please try again later ... ', true);
}
$res = $this->_insertsqlbytableforall ($path, $tables, $subsection);
}
}

Database basic Information
Private Function _retrieve () {
$backUp = ";
$backUp. = '--'. "\ n";
$backUp. = '--MySQL database dump '. "\ n";
$backUp. = '--Created by DbBackUp class, Power by Chujiu. ' . "\ n";
$backUp. = '--'. "\ n";
$backUp. = '--Host: '. $this->host. "\ n";
$backUp. = '--Date generated: '. Date (' Y '). ' Year '. Date (' m '). ' Month '. Date (' d '). ' Day '. Date (' H:i '). "\ n";
$backUp. = '--MySQL version: '. Mysql_get_server_info (). "\ n";
$backUp. = '--PHP version: '. Phpversion (). "\ n";
$backUp. = "\ n";
$backUp. = "SET sql_mode= ' No_auto_value_on_zero '; \ n";
$backUp. = "SET Time_zone = ' +00:00 '; \ 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;
}

/**
* Insert a single record
*
* @param string $row
*/
Private Function _insertsql ($row, $table) {
SQL Field comma split
$insert = ";
$insert. = "INSERT INTO". $table. "' VALUES (";
foreach ($row as $key = = $val) {
$insert. = "'". $val. "',";
}
$insert = substr ($insert, 0,-1);
$insert. = ");". "\ n";
return $insert;
}

/**
* Generate a Inser statement for a table
* @param string $table
* @param string $subsection The size of the volume
*/
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 (' database table ['. $table. '], volume '. $i. ' Write file failed, please try again later!!! ', true);
$this->_showmsg (' database table ['. $table. '], volume '. $i. ' Backup succeeded! Backup files: ['. $path. $table. $i. $this->tag. SQL] ');
$insertSqlByTable = ";
$i +=1;
}
}
Insertsqlbytable size is not large enough to be divided into volumes
if ($insertSqlByTable! = "") {
$FW = $this->writefilebybackupdata ($path. $table. $this->tag. SQL ', $insertSqlByTable);
if ($FW = = = False) $this->_showmsg (' database table ['. $table. '] Failed to write to file, please try again later!!! Backup files: ['. $path. $table. $this->tag. SQL] ', true);
$this->_showmsg (' database table ['. $table. '] Backup succeeded! Backup files: ['. $path. $table. $this->tag. SQL] ');
}
$this->_showmsg (' database table ['. $table. '] All backups are successful! ');
}

//write file
Public function Writefilebybackupdata ($fileName, $data, $method = "rb+", $iflock =1, $check =1, $chmod =1) { br> $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: Generates the path of the compressed package
* FileName: The file name to compress is usually the same directory as 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);
$inf o[] = $zip->addfile ($value, $file _name),//Avoid compressing the path of the file in the package
}
}
$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;
}

Get file
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: Generate the path to the compressed package
* @fileName: The filename to unzip is extracted to the path directory by default
*/
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;
}
}

Import Database
Public Function Importingdatabysqlfile () {

}

Timely output of information
Private Function _showmsg ($msg, $err =false) {
if ($err = = = True) {
echo "

ERROR:---". $msg. "

"; exit;
}
echo "

OK:---". $msg. "

";
}

Lock the database to avoid errors when backing up or importing
Private function Lock ($table, $op = "WRITE") {
if (mysql_query ("Lock Tables"). $table. " " . $OP))
return true;
Else
return false;
}

Unlock
Private function Unlock () {
if (mysql_query ("Unlock tables"))
return true;
Else
return false;
}

Destruction
Public Function __destruct () {
if ($this->conn) {
mysql_query ("Unlock Tables", $this->conn);
Mysql_close ($this->conn);
}
}
}
?>

http://www.bkjia.com/PHPjc/771872.html www.bkjia.com true http://www.bkjia.com/PHPjc/771872.html techarticle Backup: The table structure and data are completely separated, the default one file will record the structure of all tables, and then the table of data backup if the size of the sub-volume will be divided into multiple files, otherwise ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.