MySQL backup script, MySQL script _php tutorial

Source: Internet
Author: User
Tags ziparchive mysql automatic backup mysql backup

MySQL backup script, MySQL script


 Php//backup MySQL        Set_time_limit(0); Date_default_timezone_set (' PRC '); //Configuration    $configs=Array(        ' Host1 ' =Array(            ' localhost ', ' root ', ' root ',Array(),//back up all databases as empty, or back up those databases' D:/xampp/mysql/bin/mysqldump ',//Backup Tools            dirname(__file__)." /localhost ",//Directory plus host name5,//Delete SQL files for the first 5 days),); foreach($configs  as $config) {        $logsfile=$config[5]. ' /'.Date(' Ymd '). Log; Logs ($logsfile,$config[0]. " Backup\n "); Backup ($config); }    functionBackup$config) {        List($host,$username,$password,$databases,$backuptool,$backupdir,$day) =$config; $command= "$backuptool-U$username-H$host-P$password%s >%s "; $logsfile=$backupdir.' /'.Date(' Ymd '). Log; $backfilename=$backupdir.' /'.Date(' YMD '). " %s.sql ";//backing up the SQL file, naming the database                if(!Is_dir($backupdir)) {            mkdir($backupdir, 0755,true); }                //Delete backup files for the first 10 daysGet_dir_files ($backupdir,$returnval); if($returnval) {            foreach($returnval  as $v) {                $time=Filemtime($v); if($time<Strtotime("-$dayDay ") && (PathInfo($v, pathinfo_extension)) = = ' Zip ') {                    unlink($v); }            }        }                if(!$databases) {            $databases= Getdatabases ($host,$username,$password); }        //Start Backup        foreach($databases  as $database) {            $outputfile=sprintf($backfilename,$database); $execcommand=sprintf($command,$database,$outputfile); Try {                if(system($execcommand) ===false) {                    Throw New Exception(' Execute backup command error! ')); }                                //The file is too large to compress the failure (the test of the SQL file 4.62G, compression failed, did not create the compressed file.) Test 2.81G can)                if(file_exists($outputfile)) {                    $zip=Newziparchive (); $filename=PathInfo($outputfile,pathinfo_filename); $zipname=$backupdir.' /'.$filename.'. Zip ';//the path to the zip file                    if($zip->open ($zipname, ziparchive::overwrite) = = =true) {                        $zip->addfile ($outputfile,$filename.'.'.PathInfo($outputfile,pathinfo_extension)); $zip-Close (); }Else {                        Throw New Exception(' Ziparchive open error! '); }                }                                if(!file_exists($zipname) || (filesize($zipname) ==0)) {                    Throw New Exception(' Ziparchive Create error! '); }                                $message=Date(' y-m-d h:i:s '). "$databaseBackup complete!\r\n "; Logs ($logsfile,$message); }Catch(Exception $e) {                $message=Date(' y-m-d h:i:s ').$e->getline (). ' '.$e->getmessage (). " \ r \ n "; Logs ($logsfile,$message); }        }    }    functionGetdatabases ($host,$username,$password) {        $databases=Array(); Try {            $mysqli=NewMysqli ($host,$username,$password); $result=$mysqli->query ("Show Databases"); if($result) {                 while($row=$result-Fetch_row ()) {                    ( Current($row)! = ' Information_schema ' && Current($row)! = ' MySQL ' && Current($row)! = ' Performance_schema ') &&$databases[] = Current($row); }                $result-Free_result (); $mysqli-Close (); }Else {                Throw New Exception(' No databases! '); }        }Catch(Exception $e) {            $message=Date(' y-m-d h:i:s ').$e->getline (). ' '.$e->getmessage (). " \ r \ n "; Logs ($logsfile,$message); }                    return $databases; }        functionLogs$file,$contents) {        $dirname=dirname($file); Try {            if(!Is_dir(dirname($file)) || !is_writeable(dirname($file))) {                Throw New Exception("File is not direcotory or file can ' t write"); }            file_put_contents($file,$contents,file_append); }Catch(Exception $e) {            $message=Date(' y-m-d h:i:s ').$e->getline. ' '.$e->getmessage (). " \ r \ n "; Logs ($logfile,$message); }    }            //get the file under the current directory (without subfolders)    functionGet_dir_files ($currPath, &$returnVal=Array()) {        if(Is_dir($currPath)) {            $currPath= (substr($currPath, -1,1) = = '/')?substr($currPath, 0,strlen($currPath)-1):$currPath; if($handler=Opendir($currPath)) {                 while(($fileName=Readdir($handler)) !==false) {                    if($fileName! = '. ' &&$fileName! = '. ' &&$fileName[0]! = '. ') {                        if(Is_file($currPath. '/' .$fileName)) {                            $returnVal[] =$currPath. '/' .$fileName; }                    }                }                Closedir($handler); }        }    }?>


D:\xampp\php\php.exe-q D:\wamp\www\php_lib\basic\mysqlbackup.php

Linux system shell backup MySQL:

#!/bin/shsed's/^m//g' /home/taskschd/backup. SH #注意:The input mode of the ^m is CTRL + V, then CTRL + MDBs=(test) Root_dir=/home/backup/for in     do #备份数据 backup_dir = $ROOT _dir$dbname ' _  '$ (date +%y%m%D). sql  /usr/local/mysql/bin/mysqldump--OPT-UROOT-PABC $ dbname > $BACKUP _dir  #删除三天前数据  delete_file= $dbname'_'$ ( Date " -5 Day " " +%y%m%d ") ' . SQL '    RM $ROOT _dir$delete_file     Done

Another shell backup MySQL script:

MySQL database backup method and script under Linux system?

Method one, suitable for all forms of MySQL database, through the database export to write a script timed execution:
1. Export the entire database mysqldump-u user name-p database name > exported file name mysqldump-u wcnc-p SMGP_APPS_WCNC >/store Path/wcnc.sql
2. Export a table mysqldump-u user name-P database name table name > exported filename mysqldump-u wcnc-p smgp_apps_wcnc users>/store Path/wcnc_users.sql
3. Export a database structure mysqldump-u wcnc-p-D--add-drop-table smgp_apps_wcnc >/storage Path/wcnc_db.sql
-D No data
--add-drop-table Add a drop table before each CREATE statement
4. Import the database Common Source command into the MySQL database console:
such as Mysql-u root-p mysql>use database

Method Two, for MySQL data table format for the MyISAM
If the data file is in/var/lib/mysql
So just write a script.
Cp-r/var/lib/mysql/Backup to the folder path

Backup with rsync increments, or scheduled full backups.

Who can give me a MySQL automatic backup script

Maybe you won't use it.

You can put this script in crontab, do it every morning, and automatically back up

This script executes at most one time per day and retains only the last five days of backup on the server.


#This is a shellscript for Auto DB Backup
#Powered by Aspbiz

#设置数据库名, database login name, password, backup path, log path, data file location, and backup mode
#默认情况下备份方式是tar, it could be mysqldump,mysqldotcopy.
#默认情况下, log in to the MySQL database with root (empty) and back up to/root/dbxxxxx.tgz
#BackupMethod =mysqldump
#BackupMethod =mysqlhotcopy
#BackupMethod =tar
#Setting End

Newfile= "$BackupPath" db$ (date +%y%m%d). tgz
Dumpfile= "$BackupPath" db$ (date +%y%m%d)
Oldfile= "$BackupPath" db$ (date +%y%m%d--date= ' 5 days ago '). tgz

echo "-------------------------------------------" >> $LogFile
echo $ (date + "%y-%m-%d%h:%m:%s") >> $LogFile
echo "--------------------------" >> $LogFile
#Delete Old File
If [-F $OldFile]
Rm-f $OldFile >> $LogFile 2>&1
echo "[$OldFile]delete old File success!" >> $LogFile
echo "[$OldFile]no old Backup file! >> $LogFile

If [-F $NewFile]
echo "[$NewFile]the Backup File is Exists,can ' t backup!" >> $LogFile
Case $BackupMethod in
If [-Z $DBPasswd]
Mysqldump-u $DBUser--opt $DBName > $DumpFile
Mysqldump-u $DBUser-p$dbpasswd--opt $DBName > $DumpFile
F...... Remaining full text >> true techarticle MySQL backup script, MySQL script mysqlbackup.php: PHP//backup MySQL set_time_limit (0); Date_default_timezone_set (' PRC ');//Configuration $co Nfigs = Array (' host1 ' = Array (' Localh ...

  • Related Article

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