<?php
Class DbBackup {
Public $host = ' 127.0.0.1 '; Database address
Public $user = ' root '; Login Name
Public $pwd = ' root '; Password
Public $database; Database name
Public $charset = ' UTF8 '; Database Connection code: Mysql_set_charset
Connecting to a database
function db () {
$con = mysql_connect ($this->host, $this->user, $this->pwd);
if (! $con) {
Die (' Could not Connect ');
}
$db _selected = mysql_select_db ($this->database, $con);
if (! $db _selected) {
Die (' can\ ' t use Select db ');
}
Mysql_set_charset ($this->charset);//Set encoding
return $con;
}
An array of all the tables
function Tblist () {
$list =array ();
$rs =mysql_query ("SHOW TABLES from $this->database");
while ($temp =mysql_fetch_row ($rs)) {
$list []= $temp [0];
}
return $list;
}
Querying the table structure of all tables
function Sqlcreate () {
$sql = ";
$TB = $this->tblist ();
foreach ($tb as $v) {
$rs =mysql_query ("SHOW CREATE TABLE $v");
$temp =mysql_fetch_row ($RS);
$sql. = "-The structure of the table: {$temp [0]}--\r\n";
$sql. = "{$temp [1]}";
$sql. = ";--<xjx>--\r\n\r\n";
}
return $sql;
}
Method of Insertion
function Sqlinsert () {
$sql = ";
$TB = $this->tblist ();
foreach ($tb as $v) {
$rs =mysql_query ("SELECT * from $v");
if (!mysql_num_rows ($rs)) {//No data returned
Continue
}
$sql. = "-Data of the table: $v--\r\n";
$sql. = "INSERT into ' $v ' values\r\n";
while ($temp =mysql_fetch_row ($rs)) {
$sql. = ' (';
foreach ($temp as $v 2) {
if ($v 2===null) {
$sql. = "NULL,";
}
else {
$v 2=mysql_real_escape_string ($v 2);
$sql. = "' $v 2 ',";
}
}
$sql =mb_substr ($sql, 0,-1);
$sql. = "), \ r \ n";
}
$sql =mb_substr ($sql, 0,-3);
$sql. = ";--<xjx>--\r\n\r\n";
}
return $sql;
}
Backup operations
function Beifen ($filename) {
$this->db (); Connecting to a database
$sql = $this->sqlcreate ();
$sql 2= $this->sqlinsert ();
$data = $sql. $sql 2;
Return file_put_contents ($filename, $data);
}
Restore operations
function Huanyuan ($filename) {
$this->db (); Connecting to a database
Delete a data table
$list = $this->tblist ();
$TB = ";
foreach ($list as $v) {
$tb. = "' $v ',";
}
$TB =mb_substr ($TB, 0,-1);
if ($TB) {
$rs =mysql_query ("DROP TABLE $tb");
if ($rs ===false) {
return false;
}
}
Execute SQL
$str =file_get_contents ($filename);
$arr =explode ('--<xjx>-', $str);
Array_pop ($arr);
foreach ($arr as $v) {
$rs =mysql_query ($v);
if ($rs ===false) {
return false;
}
}
return true;
}
}
/*-------------------------------Call--------------------------------------*/
<?php
Include ("./test2.php");
$x =new dbBackup ();
$x->database= ' login ';
Backup
$rs = $x->beifen (' Db.sql ');
/ar_dump ($RS);
Restores
$rs = $x->huanyuan (' Db.sql ');
Var_dump ($RS);
< Span style= "color: #008000; Font-weight:bold "> < Span>
/span>
Backing up, recovering a database