_php tutorial for implementing MySQL database backup and Linux auto-timed backup code in PHP

Source: Internet
Author: User
Tags php write mysql backup
The article introduced two kinds of database record code, one is our PHP write common database backup class, the other is for Linux friends to provide an automatic timing backup MySQL database code, the need for students can refer to.

Save the following PHP code as a backdata.class.php file

The code is as follows Copy Code

/*
*
* Simple one MySQL backup data class
*
*/
Class backupdata{
Private $mysql _link;//Link identification
Private $dbName; Database name
Private $dataDir; The directory where the data is to be stored
private $tableNames;//Table name

Public function __construct ($mysql _link) {
$this->mysql_link = $mysql _link;
}
Public Function Backuptables ($dbName, $dataDir, $tableNames) {//Start Backup
$this->dbname = $dbName;
$this->datadir = $dataDir;
$this->tablenames = $tableNames;
$tables = $this->delarray ($this->tablenames);
$sqls = ";
foreach ($tables as $tablename) {
if ($tablename = = ") {//table does not exist
Continue
}

The following is the first half of the form of SQL **************
If a table is present, delete it first
$sqls. = "DROP TABLE IF EXISTS $tablename; n";
Reading table structure
$rs = mysql_query ("SHOW CREATE TABLE $tablename", $this->mysql_link);
$row =mysql_fetch_row ($RS);
Get table structure composed of SQL
$sqls. = $row [' 1 ']. "; nn ";
Unset ($RS);
Unset ($row);

The following is the second half of the form of SQL **************
Search out all the data in the table
$rs =mysql_query ("SELECT * from $tablename", $this->mysql_link);
Number of fields in the table
$field =mysql_num_fields ($RS);
form this type of SQL statement: "INSERT into ' groups ' VALUES (' 1499e0ca25988d ', ' director ', ' ', ' 0 ');"
while ($rows =mysql_fetch_row ($rs)) {
$comma = ";//comma
$sqls. = "INSERT into ' $tablename ' VALUES (";
for ($i =0; $i < $field; $i + +) {
$sqls. = $comma. "'". $rows [$i]. "'";
$comma = ', ';
}
$sqls. = "); nnn";
}
}
$backfilepath = $this->datadir.date ("Ymdhis", Time ()). SQL ';

Write file
$filehandle = fopen ($backfilepath, "w");
Fwrite ($filehandle, $SQLS);
Fclose ($filehandle);
}
Private Function Delarray ($array) {//Process incoming array
foreach ($array as $tables) {
if ($tables = = ' * ') {//All tables (cannot form an array in the usual way when the table name is obtained)
$newtables =mysql_list_tables ($this->dbname, $this->mysql_link);
$tableList = Array ();
for ($i = 0; $i < mysql_numrows ($newtables); $i + +) {
Array_push ($tableList, Mysql_tablename ($newtables, $i));
}
$tableList = $tableList;
}else{
$tableList = $array;
Break
}
}
return $tableList;
}
}

?>

We re-create a new file with backdata.class.php saved in the same directory

How to use:

code as follows copy code
require_once (" backdata.class.php ");
$link = @mysql_connect ("localhost", "Database name", "password") or Die (' Could not connect to server. ');
mysql_query ("Use CMS", $link);
mysql_query ("Set names UTF8", $link);
$dbbck =new backupdata ($link);//Instantiate it, as long as a link is identified on the line
//backup data, if you want to back up all the tables in a database, you can write:
$dbbck->backuptables ("CMS", "./", Array (' * '));
//When backing up data, if you want to back up only one table in a database, you can write:
$dbbck->backuptables ("CMS", "./", Array (' user '));
When backing up data, if you want to back up multiple tables in a database, you can write this:
$dbbck->backuptables ("CMS", "./", Array (' user ', ' ACL ', ' informatoin '));
Note: $dbbck->backuptables ("Parameter 1", "Parameter 2", Array ()),

Parameter 1 is: database name,
Parameter 2 is the location where the backup data is to be stored (that is, the directory address)
The third one is: you want to save those tables

The following is the code for automatic scheduled backups in Linux

Referring to many tutorials on the Web, plus your own tests, the following scripts are available for testing.

The code is as follows Copy Code

#!/bin/bash
#Shell Command for Backup MySQL Database everyday automatically by Crontab
#Author: Carlos Wong
#Date: 2010-08-24

#配置参数
User=root #数据库用户名 "> Username
Password=xxxxx #数据库用户密码
Database=tieniuzai #数据库名称
webmaster=tieniuzai@qq.com #管理员邮箱地址 to send backup failure message reminders
backup_dir=/var/www/data_backup/topons/#备份文件存储路径
Logfile=/var/www/data_backup/topons/data_backup.log #日记文件路径
Date= ' Date ' +%y%m%d-%h%m ' #日期格式 (as file name)
dumpfile= $DATE. SQL #备份文件名
Archive= $DATE. Sql.tgz #压缩文件名
Options= "-u$user-p$password–opt–extended-insert=false–triggers=false-r–hex-blob–flush-logs–delete-master-logs- B $DATABASE "#mysqldump parameter details see Help Mysqldump-help

#判断备份文件存储目录是否存在, otherwise create the directory
if [!-D $BACKUP _dir];
Then
Mkdir-p "$BACKUP _dir"
Fi

#开始备份之前, writes the backup information header to the journal file
echo "" >> $LOGFILE
echo "" >> $LOGFILE
echo "——————————————— –" >> $LOGFILE
echo "BACKUP Date:" $ (date + "%y-%m-%d%h:%m:%s") >> $LOGFILE
echo "——————————————— –" >> $LOGFILE

#切换至备份目录
CD $BACKUP _dir
#使用mysqldump command Backup to make a database and name the backup file with a formatted timestamp
Mysqldump $OPTIONS > $DUMPFILE
#判断数据库备份是否成功
if [[$ = = 0]]; Then
#创建备份文件的压缩包
Tar czvf $ARCHIVE $DUMPFILE >> $LOGFILE 2>&1
#输入备份成功的消息到日记文件
echo "[$ARCHIVE] Backup successful! >> $LOGFILE
#删除原始备份文件, just keep the archive of your database backup files
Rm-f $DUMPFILE
Else
echo "Database Backup fail!" >> $LOGFILE

#备份失败后向网站管理者发送邮件提醒, support is required for mailutils or similar terminal messaging tools
#mail-S "Database: $DATABASE Daily Backup Fail" $WEBMASTER
Fi
#输出备份过程结束的提醒消息
echo "Backup Process Done"

Use:

Save the above code to:/usr/sbin/databackup (the file name is arbitrary, as long as the system does not have the same name as the original command, the code can be placed anywhere, placed in the Sbin directory just for the convenience of execution, sbin directory of files/directories can be directly called in the terminal, Similar to the directory specified by the path variable under Windows)
Add executable permissions to the script: sudo chmod +x/usr/sbin/databackup
Execute script: sudo databackup
If you need to perform a backup command on a timed basis, simply place the following code in the crontab file (sudo vim/etc/crontab):
3 * * * root/usr/sbin/databackup #它代表着将于每天3点执行DataBackup脚本

Little attention to the following:

The shell script definition variables under Linux are in the format: key=value, note that they cannot have spaces before or after the "=" between them, or the system cannot confirm the variable.
The line marked in red, the first character "'" that resembles a single quotation mark is not a single quotation mark, and its input key is below the keyboard Esc key.
This script is only suitable for backups of some small sites because it is a full backup of the database instead of an incremental backup, and is not suitable for large-capacity database backups.

Compared to the two methods of timing backup is the best way to save time so that the machine at least people access to the automatic filing, and PHP backup class requires human action, of course, under Windows can also take advantage of planning tasks to achieve.

http://www.bkjia.com/PHPjc/632935.html www.bkjia.com true http://www.bkjia.com/PHPjc/632935.html techarticle This article introduces two kinds of database record code, one is the common database backup class which we write in PHP, the other is the code which provides the Linux friend with the automatic timing backup MySQL database ...

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