PHP Backup Database principles and methods 57

Source: Internet
Author: User
Tags explode setcookie strlen

1, the principle of PHP backup Database
Find all tables-Find all fields (need to list all field names, field types and other related letters)
---Find all the data (read the data to note the conversion of special symbols addslashes
())--Generate SQL (format the data to generate the corresponding SQL)
Output SQL related information through related functions, and format the file, save!
2. mysql related functions in PHP
Mysql_list_tables () Table query function, similar to the mysql_query () function
Mysql_fetch_field () field information function, return handle
Name of Field
Name of the data table to which the table field belongs
Type field max_length The maximum length of the field not_null field is not
Is null, yes, then the value of this item is whether the 1primary_key field is the primary key, yes, then this
The value of an item is whether the 1unique_key field is a unique key, yes, the value of this item is
If the 1multiple_key field is not a unique key, yes, the value of this item is 1
Whether the Numeric field is a numeric type, yes, the value of this item is whether the 1Blob field is
Blob type, yes, then the value of this item is 1
Unsigned whether the field of the numeric type is Unsigned, yes, the value of this item is 1
Zerofill If the field for the numeric type is zerofilled Yes, the value of this item is 1

CREATE TABLE ' help_category ' (' help_category_id ' int (5)
unsigned not NULL, ' name ' char (+) NOT NULL)
3, Backup time precautions 1, attention to the size of the database, too large or too many tables
Fragment processing 2, the generated SQL file name or storage is not easy to guess 3, backup health
Files can be saved in a table or automatically for 4, you can use the zip component to compress the generated
File to keep
----------------------------------------Mini
Version----------------------------------------------------
<?php
$mysql _dbname = "php100";
mysql_connect ("localhost", "root", "");
mysql_select_db ($mysql _dbname);

$sql _list = mysql_list_tables ($mysql _dbname);
while ($row _data = mysql_fetch_row ($sql _list)) {
Echo $row _data[0]. "<br>";
GET_TABLE_FD ($row _data[0], "SQL");

$FP =fopen ("sql/$tablename. sql", "w+");
Fwrite ($fp, $field);
Fclose ($FP);
}

function Get_table_fd ($tablename) {
$field = "CREATE TABLE ' $tablename ' (\ n";
$result = mysql_query ("SELECT * from $tablename");
while ($meta = Mysql_fetch_field ($result)) {
if ($meta->not_null)
$not _null = "Not_null";
$field. = "' $meta->name ' $meta->type ($meta->max_length)
$not _null; \ n ";
}
$field. = ") \ n";
return $field;
}


?>


-------------------------------------------------Zhang Emming
Version-----------------------------------------
<?php
---the variable information that needs to be set
$user = "admin";//system administrator user name
$pass = "e10adc3949ba59abbe56e057f20f883e";//the password is MD5
Encrypted value, the initial value is 123456, the password format can also be written as: $pass = MD5
("123456");
$url = "http://localhost/PHP/";//URL settings, you must configure the URL, no
Then the system is going to go wrong oh! Remember that there must be "/" in the end
$lang = "GBK";//The function is when the database is to be imported, if MySQL is higher than version 4.0.x
In this case, you need to set the language encoding format! hehe ~

----start from here, you don't have to set it up Oh! The following information is irrelevant!
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbdata = "";

Header ("content-type:text/html; CHARSET=GBK ");
Error_reporting (E_all & ~e_notice);
Ob_start ();
@set_time_limit (0);
Function error ($msg = "", $url 2= "index.php")
{
Global $url;
Die ("<script language=javascript>alert (' Friendship tip: \\n\\n\\t").
$msg. " \\n '), location.href= ' ". $url. $url 2." ' </script> ");
return true;
}

function Set_sql_cookie ($act = "Backup")
{
Global $url, $dbhost, $dbuser, $dbpass, $dbdata;
echo "<title> Set Database Information-PHP100 backup system </title>\n";
echo "<style type= ' text/css ' >\nbody\n{\tbody:normal 14px ' song body
', ' Tahoma ', ' Arial '; \n}\n</style>\n ';
echo "Please set the database server, account number, password and database name and other parameters of the letter
Interest! ";
echo "<form method= ' post ' action= '". $url. " Index.php?act= ".
$act. " &set=cookie ' >\n ';
echo "Server <input type= ' text ' name= ' db_host ' value= '".
$dbhost. "' style= ' width:150px;height:20px; ' ><br/>\n ";
echo "Account &nbsp; Number <input type= ' text ' name= ' db_user ' value= ' ".
$dbuser. "' style= ' width:150px;height:20px; ' ><br/>\n ";
echo "Secret &nbsp; Yards <input type= ' password ' name= ' Db_pass '
Value= ' ". $dbpass." ' style= ' width:150px;height:20px; ' ><br/>\n ";
echo "Name &nbsp; Called <input type= ' text ' name= ' db_data ' value= ' ".
$dbdata. "' style= ' width:150px;height:20px; ' ><br/><br/>\n ";
echo "<input type= ' submit ' value= ' confirmation ' > <input type= ' reset '
Value= ' reset ' ></form>\n ';
Die ();
return true;
}

function Chk_get_set ($act = "Backup")
{
Global $url, $dbhost, $dbuser, $dbpass, $dbdata;
$db _host = $_post["Db_host"];
$db _user = $_post["Db_user"];
$db _pass = $_post["Db_pass"];
$db _data = $_post["Db_data"];
if (Empty ($db _host) | | empty ($db _user) | | empty ($DB _data)) error
("Database server, account and database name is not empty", "index.php?act=".
$act);
@mysql_connect ($db _host, $db _user, $db _pass) or error ("Cannot connect
On the server, please check "," index.php?act= ". $act);
@mysql_select_db ($db _data) or error ("Unable to connect to the database! Please check
! "," index.php?act= ". $act);
$msg = $act = = "Recover"? "Restore": "Backup";
if ($act = = "Backup" &&!file_exists ($db _data) mkdir
($db _data);//CREATE DATABASE name!
if ($act = = "Recover" &&!file_exists ($db _data)) Error ("folder".
$db _data. "Not there! "," index.php?act= ". $act);
Setcookie ("qinggan_db", $db _host. " ___ ". $db _user." ___".
$db _pass. " ___ ". $db _data);//Set cookies on the server
@mysql_close ();//Close database connection
Error ("The database information has been configured and will proceed to the next step: \\n\\n\\t\\t.")
$msg. " Data! "," index.php?act= ". $act);
return true;
}

function Sql_connect ($cookie _db)
{
Global $lang;
$dbarray = Explode ("___", $cookie _db);
mysql_connect ($dbarray [0], $dbarray [1], $dbarray [2]);//connection Information
if (Mysql_get_server_info () > "4.1") mysql_query ("SET NAMES").
$lang. "'");
if (Mysql_get_server_info () > "5.0.1") mysql_query ("SET
Sql_mode= ' ");
mysql_select_db ($dbarray [3]);
return true;
}

function Sql_query ($sql = "")
{
if (empty ($sql)) return false;
$query = mysql_query ($sql);
return $query;
}

function Sql_fetch_array ($query)
{
if (empty ($query)) return false;
$rows = Mysql_fetch_array ($query);
return $rows;
}

function Table2sql ($table)
{
$tabledump = "DROP TABLE IF EXISTS". $table. "; n ";
$query = Sql_query ("SHOW CREATE TABLE". $table);
$rows = Sql_fetch_array ($query);
$tabledump. = $rows [1]. "; N\n ";
return $tabledump;
}

function errmsg ($msg = "", $url 2= "index.php")
{
Global $url;
echo "<script language=" JavaScript ">\nfunction movenew ()
{\nlocation.href= "". $url. $url 2. ""; N}\nwindow.settimeout
(' Movenew () ', ';\n</script> ');
Echo $msg;
echo "<br/><br/>";
echo "If your system does not support jumps or the system does not jump for a long time, please manually click on the operator
For ";
echo "<input type= ' button ' onclick=" window.location= ' ". $url.
$url 2. "'" Value= ' manual click Jump ' > ';
Die ();
return true;
}

function Read_msg ($file)
{
if ([email protected] ($file, "RB"))
{
$file _data=fread ($handle, FileSize ($file));
Fclose ($handle);
}
return $file _data;
}

function Recover_data ($sql)
{
$sql =str_replace ("\ r", "\ n", $sql);
$sql _array=explode ("; \ n", $sql);
foreach ($sql _array as $key = $value)
{
$value = Trim ($value);
if ($value = = "#" | | $value = = "--")
{
$queryy = explode ("\ n", $value);
$value = ";
foreach ($queryy as $v 2)
{
if ($v 2[0]!= ' # ') $value. = $v 2;
}
}
if ($value)
{
$value =trim (str_replace ("\ n", "", $value));
if (Get_cfg_var ("MAGIC_QUOTES_GPC")) stripslashes ($value);
Sql_query ($value);
}
}
return true;
}

$cookie _chk = $_cookie["Qinggan_userchk"];
$cookie _db = $_cookie["qinggan_db"];
if ($cookie _chk)
{
if ($cookie _chk! = $user. " ___ ". MD5 ($pass)) header (" Location: ".
$url. " Index.php ");
}
$act = $_get["Act"]? $_get["Act"]: $_post["act";
@ $act _set = $_get["Set"];
if ($act = = "Backup")
{
Echo "<title> currently backing up information ...-PHP100 website backup system-
Www.php100.com</title> ";
if (Empty ($cookie _chk)) error ("Requires user authentication account and password!") ");
if ($act _set = = "Cookie") Chk_get_set ($act);
if (Empty ($cookie _db)) Set_sql_cookie ($act);
Sql_connect ($cookie _db);//Connect to Database
$dbarray = Explode ("___", $cookie _db);
$table _list = Mysql_list_tables ($dbarray [3]);//List all tables
$table _count = mysql_num_rows ($table _list);//hehe Get the total number of tables
if (!file_exists ($dbarray [3]. " /". $dbarray [3].". SQL "))
{
-----Backing up data table information
$array = Array ();
for ($i =0; $i <mysql_num_rows ($table _list); $i + +)
{
$table = Mysql_tablename ($table _list, $i);//
$array [$i] = Table2sql ($table);
}
$msg = implode ("\ n", $array);
$handle = fopen ($dbarray [3]. " /". $dbarray [3].". SQL "," WB ");
if (!get_cfg_var ("MAGIC_QUOTES_GPC")) addslashes ($msg);
Fputs ($handle, $msg);
Fclose ($handle);
Unset ($msg);
}
-----form
@ $tableid = $_get["TableID"]? Intval ($_get["TableID"]): 0;
@ $startid = $_get["Startid"]? Intval ($_get["Startid"]): 0;
@ $pageid = $_get["PageID"]? Intval ($_get["PageID"]): 0;
-----Start Content Backup
if (($tableid + 1) < $table _count)
{
$table = Mysql_tablename ($table _list, $tableid);
$query = Sql_query ("SELECT count (*) as Count from". $table. " `");
$num = Sql_fetch_array ($query);
$count = $num ["Count"];//gets the number
$per _size = 1000;//Maximum number not exceeding 1000
if ($count < $per _size) $per _size = $count;
if ($count && $startid < $count)
{
$query = Sql_query ("SELECT * from". $table. " ' Limit '. $startid. ",".
$per _size);//
$numfields = Mysql_num_fields ($query);
$tabledump = "";
while ($rows = Mysql_fetch_row ($query))
{
$tabledump. = "INSERT into $table VALUES (";
$comma = ";
for ($i = 0; $i < $numfields; $i + +)
{
$tabledump. = $comma. (' \ '. mysql_escape_string ($rows [$i]). ' \‘‘);
$comma = ', ';
}
$tabledump. = "); \ n";
//---------------
$startid + +;
if (strlen ($tabledump) > (2048*1024))
{
$handle = fopen ($dbarray [3]. " /". $table." _ ". $pageid.". SQL. "," WB ");
if (!get_cfg_var ("MAGIC_QUOTES_GPC")) addslashes ($tabledump);
Fputs ($handle, $tabledump);
Fclose ($handle);
Unset ($tabledump);//Clear the contents!
ErrMsg ("Backing up data Table". $table. "Information, currently written in section."
($pageid + 1). " Page, which is about to be written to section. ($pageid +2). " Page letter
"Index.php?act=backup&tableid=". $tableid. " &startid= ".
($startid). " &pageid= ". ($pageid + 1));
}
}
//----
if ($tabledump)
{
if ($pageid >0)
{
@ $msg = file_get_contents ($dbarray [3]. " /". $table." _". ($pageid-
1). ". SQL ");
if (strlen ($msg) < (2048*1024))
{
$handle = fopen ($dbarray [3]. " /". $table." _". ($pageid-
1). ". SQL "," AB ");
if (!get_cfg_var ("MAGIC_QUOTES_GPC")) addslashes ($tabledump);
Fputs ($handle, $tabledump);
Fclose ($handle);
Unset ($tabledump, $msg);
$newpageid = $pageid;
}
Else
{
$handle = fopen ($dbarray [3]. " /". $table." _ ". $pageid.". SQL "," WB ");
if (!get_cfg_var ("MAGIC_QUOTES_GPC")) addslashes ($tabledump);
Fputs ($handle, $tabledump);
Fclose ($handle);
Unset ($tabledump);
$newpageid = $pageid + 1;
}
}
Else
{
$handle = fopen ($dbarray [3]. " /". $table." _ ". $pageid.". SQL "," WB ");
if (!get_cfg_var ("MAGIC_QUOTES_GPC")) addslashes ($tabledump);
Fputs ($handle, $tabledump);
Fclose ($handle);
Unset ($tabledump);
$newpageid = $pageid + 1;
}
}
if ($startid < $count)
{
ErrMsg ("Backing up data Table". $table. "Information. "," index.php?
Act=backup&tableid= ". $tableid." &startid= ".
($startid). " &pageid= ". $newpageid);
}
Else
{
//------
ErrMsg ("Datasheet". $table. "The information has been backed up and the next number is started
According to the table! "," index.php?act=backup&tableid= ". ($tableid + 1));
}
}
Else
{
ErrMsg ("Datasheet". $table. "The information is empty and the next data table information is started
"," index.php?act=backup&tableid= ". ($tableid + 1));
}
}
Else
{
Setcookie ("qinggan_db", "");//Clear Database cookie Information
Setcookie ("Qinggan_userchk", "");//Clear User authentication information
Error ("The data has been backed up!") "," index.php ");
}
}
ElseIf ($act = = "Recover")
{
echo "<title> Recover data Sheet information-PHP100 website backup system-
Www.php100.com</title> ";
if (Empty ($cookie _chk)) error ("Requires user authentication account and password!") ");
if ($act _set = = "Cookie") Chk_get_set ($act);
if (Empty ($cookie _db)) Set_sql_cookie ($act);
Sql_connect ($cookie _db);//Connect to Database
$dbarray = Explode ("___", $cookie _db);
$sql = Read_msg ($dbarray [3]. " /". $dbarray [3].". SQL ");
Recover_data ($sql);
ErrMsg ("Data table structure has been restored, recovering data information!") "," index.php?
Act=recover_data ");
}
ElseIf ($act = = "Recover_data")
{
echo "<title> Recover data-PHP100 website backup system-
Www.php100.com</title> ";
if (Empty ($cookie _chk)) error ("Requires user authentication account and password!") ");
if ($act _set = = "Cookie") Chk_get_set ($act);
if (Empty ($cookie _db)) Set_sql_cookie ($act);
Sql_connect ($cookie _db);//Connect to Database
$dbarray = Explode ("___", $cookie _db);
//-----
$table _list = Mysql_list_tables ($dbarray [3]);//List all tables
$table _count = mysql_num_rows ($table _list);//hehe Get the total number of tables
$tableid = $_get["TableID"]? Intval ($_get["TableID"]): 0;
$pageid = $_get["PageID"]? Intval ($_get["PageID"]): 0;
$table = Mysql_tablename ($table _list, $tableid);
if (($tableid + 1) < $table _count)
{
if (!file_exists ($dbarray [3]. " /". $table." _ ". $pageid.". SQL "))
{
ErrMsg ("Data Sheet". $table. "Information does not exist or has not been backed up! "," index.php?
Act=recover_data&tableid= ". ($tableid + 1));
}
$sql = Read_msg ($dbarray [3]. " /". $table." _ ". $pageid.". SQL ");
if ($sql) recover_data ($sql);
if (File_exists ($dbarray [3]. " /". $table." _". ($pageid + 1). ". SQL "))
{
ErrMsg ("Recovering data Table". $table. "Info", "index.php?"
Act=recover_data&tableid= ". $tableid." &pageid= ". ($pageid + 1));
}
Else
{
ErrMsg ("Data table already recovered". $table. "Information that will restore the next data table information
! "," index.php?act=recover_data&tableid= ". ($tableid + 1));
}
}
Else
{
Setcookie ("Qinggan_userchk", "" ");
Setcookie ("qinggan_db", "" ");
Error ("Data information has been restored!") "," index.php ");
}
}
ElseIf ($act = = "Check")
{
$chk _user = $_post["Chk_user"];
$chk _pass = $_post["Chk_pass"];
if (Empty ($chk _user) | | empty ($CHK _pass)) error ("Account or password cannot be
Empty ");
if ($chk _user! = $user | | MD5 ($CHK _pass)! = $pass) Error ("Account or secret
Code is not correct! ");
Setcookie ("Qinggan_userchk", $chk _user. " ___ ". MD5 ($pass));//settings
Cookie Information
?>
<title> Select Action Item-PHP100 website backup system-
Www.php100.com</title>
<style type= "Text/css" >
Body
{
Font:normal 14px ' song Body ', ' Tahoma ', ' Arial ';
}
</style>
Please select the item you want to work with! <br/><br/>
<input type= "button" onclick= "window.location= ' index.php?"
Act=backup ' "value=" Backup Data "><br/><br/>
<input type= "button" onclick= "window.location= ' index.php?"
Act=recover&iftable=yes ' "value=" recovery data "><br/>
<?php
}
Else
{
Setcookie ("Qinggan_userchk", "" ");
Setcookie ("qinggan_db", "" ");
?>
<title> verified Account-PHP100 website backup system-
Www.php100.com</title>
<style type= "Text/css" >
Body
{
Font:normal 14px ' song Body ', ' Tahoma ', ' Arial ';
}
</style>
You need to enter your account and password to confirm your identity before the operation!
<form method= "POST" action= "Index.php?act=check" >
Account: <input type= "text" Name= "Chk_user"
Style= "width:150px;height:20px;" ><br/>
Password: <input type= "password" name= "Chk_pass"
Style= "width:150px;height:20px;" ><br/><br/>
<input type= "Submit" value= "confirm" > <input type= "Reset"
Value= "Refill" ></form>
<?php
}
Ob_end_flush ();
?>
<br/><br/>
Backup principle:

<blockquote>
<li> a table and a file! <a href= "http://www.php100.com" >php100 number
Database backup System </a>
<li> Create new files automatically when a single table file is larger than 2048K!
<li> first generation of data structure tables! This table plays a master role!
<li> is not the same as the current mainstream backup program! The system generates SQL files--compatibility
The table created by phpMyAdmin is not validated!
</blockquote>

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.