Linux PHP MySQL database backup implementation Code _php tutorial

Source: Internet
Author: User
Tags session id php mysql
But there was a problem:
First, running PHP is a apche user, such as nobody, then it is generally not authorized to access the/usr/local/mysql/data directory
Second, even if you can access, then how can you copy the files in the/usr/local/mysql/data directory? Because MySQL is running without running access, then the nobody user has permission to stop the MySQL service, impossible!
The more I think the more wrong, there is no way to see if you can start from PHP operation database, so went to see the next phpMyAdmin and discuz! Of the code, OH, so stole a copy of the discuz! Code that forms the following method of backing up the database. (Thanks to discuz! here of developers)

There are two ways to back up a database, one is to back up only the structure of the database, one to back up the structure and all the data, and of course the second method is OK, but I do it for the sake of considering the possible needs.


/****** backing up the database structure ******/

/*
Function name: Table2sql ()
function function: Convert the structure of a table into SQL
Function parameters: $table: The name of the table to extract
Return value: Returns the extracted result, SQL collection
Function Author: heiyeluren
*/

function Table2sql ($table)
{
Global $db;
$tabledump = "DROP TABLE IF EXISTS $table; \ n";
$createtable = $db->query ("SHOW CREATE TABLE $table");
$create = $db->fetch_row ($createtable);
$tabledump. = $create [1]. "; N\n ";

return $tabledump;
}


/****** backing up the database structure and all data ******/
/*
Function name: Data2sql ()
function function: Convert the structure and data of a table into SQL
Function parameters: $table: The name of the table to extract
Return value: Returns the extracted result, SQL collection
Function Author: heiyeluren
*/
function Data2sql ($table)
{
Global $db;
$tabledump = "DROP TABLE IF EXISTS $table; \ n";
$createtable = $db->query ("SHOW CREATE TABLE $table");
$create = $db->fetch_row ($createtable);
$tabledump. = $create [1]. "; N\n ";

$rows = $db->query ("SELECT * from $table");
$numfields = $db->num_fields ($rows);
$numrows = $db->num_rows ($rows);
while ($row = $db->fetch_row ($rows))
{
$comma = "";
$tabledump. = "INSERT into $table VALUES (";
for ($i = 0; $i < $numfields; $i + +)
{
$tabledump. = $comma. "'". Mysql_escape_string ($row [$i]). "'";
$comma = ",";
}
$tabledump. = "); \ n";
}
$tabledump. = "\ n";

return $tabledump;
}


/****** specific implementation of the Operation ******/
Well, since we have written the code, then how do we implement the backup in the specific program, we look at the following code.


/* Back up the database */
Note: Our database operation uses the Phplib DB class

Define the data tables, prefixes, and where to save
$tables = Array (' Us_sort ', ' us_download ', ' us_article ', ' Us_guestbook '); Define the data table to be saved, an array
$prefix = ' Us_ '; The prefix of the. sql file to save.
$saveto = ' server '; Where to save to, local or server, default is server
$back _mode = ' all '; How you want to save it all, or just the database structure
$admin = ' Heiyeluren '; Administrator name
$admin _email = ' heiyeluren@163.com '; Admin Mailbox

Define file names for data saving
$local _filename = $prefix. Date (' Ymd_his '). SQL "';
if (! $filename) {$filename = $db _backup_path. $prefix. Date (' Ymd_his_ '). Create_check_code (4). ". SQL"; }
$filename = $prefix. Date (ymd_his). Create_check_ Code (6). ". SQL "; File name saved on the server
Note the following Create_check_code () function, which is a function that generates random codes, which can be consulted in detail:
Http://www.jb51.net/article/17423.htm

Get database structure and data content
foreach ($tables as $table)
{
if ($back _mode = = ' All ') {$sqldump. = Data2sql ($table);}
if ($back _mode = = ' table ') {$sqldump. = Table2sql ($table);}
}

Start saving if the data contents are not empty
if (Trim ($sqldump))
{
Write Start information
$sqldump =
"#--------------------------------------------------------\ n".
"# data table backup \ n".
"#\n".
"# Server: $db->host\n".
"# Database: $db->database\n".
"# Backup number:". CREATE_SESS_ID (). " \ n ". Here is a function to generate session ID
"# Backup time:". Time_to_date (', 6). " \ n ". This is the function that gets the current time.
"#\n".
"# Administrator: $admin ($admin _email) \ n". Administrator's user name and email address
"# $copyright \ n".
"#--------------------------------------------------------\n\n\n."
$sqldump;

Save to Local
if ($saveto = = "local")
{
Ob_end_clean ();
Header (' Content-encoding:none ');
Header (' Content-type: '. ( Strpos ($HTTP _server_vars[' http_user_agent '], ' MSIE ')? ' Application/octetstream ': ' Application/octet-stream ');
Header (' Content-disposition: '. ( Strpos ($HTTP _server_vars[' http_user_agent '], ' MSIE ')? ' Inline; ': ' Attachment; ').' Filename= "'. $local _filename);
Header (' Content-length: '. strlen ($sqldump));
Header (' Pragma:no-cache ');
Header (' expires:0 ');
Echo $sqldump;
}
Save to local end

Save on server
if ($saveto = = "Server")
{
if ($filename! = "")
{
@ $fp = fopen ($filename, "w+");
if ($FP)
{
@flock ($FP, 3);
if (@!fwrite ($FP, $sqldump))
{
@fclose ($FP);
Exit_msg ("The data file cannot be saved to the server, check the directory properties if you have permission to write.") ");
}
Else
{
Exit_msg ("The data was successfully backed up to the server $filename. ");
}
}
Else
{
Exit_msg ("Could not open the directory you specified." $filename. ", determine if the directory exists, or if it has appropriate permissions");
}
}
Else
{
Exit_msg ("You have not entered a backup file name, please return the modification. ");
}
}
Save to server end
}
Else
{
EXIT_MSG ("Data sheet without any content");
}

/* BACKUP DATABASE End */



Oh, basically this is the end, and then the question is how to restore data to the database, I think this is not complex, but it is best to meet the ability to recover data from the client and from the server.

http://www.bkjia.com/PHPjc/319938.html www.bkjia.com true http://www.bkjia.com/PHPjc/319938.html techarticle But there is a problem: first, run PHP is apche users, such as nobody, then it is generally not authorized to access the/usr/local/mysql/data directory of the second, even if you can access, that ...

  • 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.