Home php教程 php手册 php中实现mysql数据库备份与linux自动定时备份代码

php中实现mysql数据库备份与linux自动定时备份代码

Jun 13, 2016 am 09:49 AM
linux mysql php and code backup Filing timing accomplish database article of automatic

文章介绍了二种数据库备案的代码,一种是我们php写的常用的数据库备份类,另一种是为linux朋友提供的一个自动定时备份mysql数据库的代码,有需要的同学可以参考一下。

把下面php代码保存成backdata.class.php文件

 代码如下 复制代码

/*
*
*简单的一个Mysql备份数据类
*
*/
class backupData{
    private    $mysql_link;//链接标识
    private    $dbName;    //数据库名
    private    $dataDir;     //数据所要存放的目录
    private    $tableNames;//表名

    public function __construct($mysql_link){
         $this->mysql_link = $mysql_link;
    }
    public function backupTables($dbName,$dataDir,$tableNames){//开始备份
        $this->dbName  = $dbName;
        $this->dataDir  = $dataDir;
        $this->tableNames = $tableNames;
        $tables=$this->delarray($this->tableNames);
        $sqls='';
        foreach($tables as $tablename){
            if($tablename==''){//表不存在时
                continue;
            }
           
            //************************以下是形成SQL的前半部分**************
            //如果存在表,就先删除
            $sqls .= "DROP TABLE IF EXISTS $tablename;n";
            //读取表结构
            $rs = mysql_query("SHOW CREATE TABLE $tablename",$this->mysql_link); 
            $row=mysql_fetch_row($rs);
            //获得表结构组成SQL
            $sqls.=$row['1'].";nn";
            unset($rs);
            unset($row);
           
            //************************以下是形成SQL的后半部分**************
            //查寻出表中的所有数据
            $rs=mysql_query("select * from $tablename",$this->mysql_link);
            //表的字段个数
            $field=mysql_num_fields($rs);
            //形成此种SQL语句:"INSERT INTO `groups` VALUES('1499e0ca25988d','主任','','0');"
            while($rows=mysql_fetch_row($rs)){
                $comma='';//逗号
                $sqls.="INSERT INTO `$tablename` VALUES(";
                for($i=0;$i                     $sqls.=$comma."'".$rows[$i]."'";
                    $comma=',';
                }
                $sqls.=");nnn";
            }
        }
        $backfilepath=$this->dataDir.date("Ymdhis",time()).'.sql';
       
        //写入文件
        $filehandle = fopen($backfilepath, "w");
        fwrite($filehandle, $sqls);
        fclose($filehandle);
    }
    private function delarray($array){    //处理传入进来的数组
        foreach($array as $tables){
            if($tables=='*'){    //所有的表(获得表名时不能按常规方式来组成一个数组)
                $newtables=mysql_list_tables($this->dbName,$this->mysql_link);
                $tableList = array();
                for ($i = 0; $i                     array_push($tableList,mysql_tablename($newtables, $i));
                }
                $tableList=$tableList;
            }else{
                $tableList=$array;
                break;
            }
        }
        return $tableList;
    }
}

?>

我们再创建一个新的文件与backdata.class.php保存在同一目录

使用方法:

 代码如下 复制代码
require_once("backdata.class.php");
$link = @mysql_connect("localhost","数据库名","密码") or die ('Could not connect to server.');
mysql_query("use cms",$link);
mysql_query("set names utf8",$link);
$dbbck=new backupData($link);//实例化它,只要一个链接标识就行了
//备份数据时,如想备份一个数据库中的所有表,你可这样写:
$dbbck->backupTables("cms","./",array('*'));
//备份数据时,如想备份一个数据库中的仅一个表时,你可这样写:
$dbbck->backupTables("cms","./",array('user'));
//备份数据时,如想备份一个数据库中的多个表时,你可这样写:
$dbbck->backupTables("cms","./",array('user','acl','informatoin'));
//注解:$dbbck->backupTables("参1","参2",array());中,

参1为:数据库名,
参2为:要存放备份数据的位置(即目录地址)
第三个为:你要保存那些表

 

下面为linux中的自动定时备份的代码

参考了网上的很多教程,外加自己的测试,以下脚本经测试可用。

 代码如下 复制代码

#!/bin/bash
#Shell Command For Backup MySQL Database Everyday Automatically By Crontab
#Author : Carlos Wong
#Date : 2010-08-24

#配置参数
USER=root #数据库用户名" >用户名
PASSWORD=××××× #数据库用户密码
DATABASE=TIENIUZAI    #数据库名称
WEBMASTER=tieniuzai@qq.com #管理员邮箱地址,用以发送备份失败消息提醒
BACKUP_DIR=/var/www/Data_Backup/topons/ #备份文件存储路径
LOGFILE=/var/www/Data_Backup/topons/data_backup.log #日记文件路径
DATE=`date ‘+%Y%m%d-%H%M’` #日期格式(作为文件名)
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 参数 详情见帮助 mysqldump -help

#判断备份文件存储目录是否存在,否则创建该目录
if [ ! -d $BACKUP_DIR ] ;
then
mkdir -p “$BACKUP_DIR”
fi

#开始备份之前,将备份信息头写入日记文件
echo ” ” >> $LOGFILE
echo ” ” >> $LOGFILE
echo “———————————————–” >> $LOGFILE
echo “BACKUP DATE:” $(date +”%y-%m-%d %H:%M:%S”) >> $LOGFILE
echo “———————————————– ” >> $LOGFILE

#切换至备份目录
cd $BACKUP_DIR
#使用mysqldump 命令备份制定数据库,并以格式化的时间戳命名备份文件
mysqldump $OPTIONS > $DUMPFILE
#判断数据库备份是否成功
if [[ $? == 0 ]]; then
#创建备份文件的压缩包
tar czvf $ARCHIVE $DUMPFILE >> $LOGFILE 2>&1
#输入备份成功的消息到日记文件
echo “[$ARCHIVE] Backup Successful!” >> $LOGFILE
#删除原始备份文件,只需保 留数据库备份文件的压缩包即可
rm -f $DUMPFILE
else
echo “Database Backup Fail!” >> $LOGFILE

#备份失败后向网站管理者发送邮件提醒,需要mailutils或者类似终端下发送邮件工具的支持
#mail -s “Database:$DATABASE Daily Backup Fail” $WEBMASTER
fi
#输出备份过程结束的提醒消息
echo “Backup Process Done”

使用:

将以上代码保存到: /usr/sbin/DataBackup     (文件名随意,只要不跟系统原有的命令同名即可;代码可以放到任何地方,放在sbin目录下只是为了方便执行,sbin目录下的文件/目录可在终端直接调 用,类似于windows下PATH变量指定的目录)
为脚本添加可执行权限:  sudo chmod +x  /usr/sbin/DataBackup
执行脚本: sudo  DataBackup
如果需要定时执行备份命令的,只需将下面这段代码放到crontab 文件(sudo vim /etc/crontab)中去就可以了:
01 3 * * * root /usr/sbin/DataBackup    #它代表着将于每天3点执行DataBackup脚本

小注意一下下:

linux 下的shell脚本定义变量的格式为:  key=value  ,注意他们两者之间的” = “前后不能出现空格,否则系统无法确认该变量。
用红色标注的那行,第一个类似单引号的字符”`”其实不是单引号,它的输入键在键盘ESC键下方。
这个脚本只适合用于一些小站点的备份,因为它是对数据库进行全部备份而不是增量备份,不适合大容量的数据库备份。

相对于两种方法定时备份算是最好的方法了,这样可以节省时间让机器在最少人访问时自动备案,而php备份类需要人为操作,当然在windows下也可以利用计划任务来实现了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

macOS and Linux: Compatibility and User Experience macOS and Linux: Compatibility and User Experience Apr 30, 2025 am 12:05 AM

macOS and Linux have their own advantages in compatibility and user experience. macOS has excellent compatibility within the Apple ecosystem, and the user experience is simple and intuitive; Linux has outstanding hardware compatibility and software flexibility. The user experience varies from distribution to distribution, emphasizing personalization and control.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

See all articles