Table of Contents
MySQL backup script, mysql script
mySQL database backup under linux system Methods and scripts?
Who can give me a script for automatic backup of MYSQL
Home Backend Development PHP Tutorial MySQL backup script, mysql script_PHP tutorial

MySQL backup script, mysql script_PHP tutorial

Jul 13, 2016 am 10:23 AM
mysql database

MySQL backup script, mysql script

mysqlbackup.php:

<?<span>php

    </span><span>//</span><span>备份mysql</span>
    
    <span>set_time_limit</span>(0<span>);
    date_default_timezone_set(</span>'PRC'<span>);
    
    </span><span>//</span><span>配置</span>
    <span>$configs</span> = <span>array</span><span>(
        </span>'host1'=><span>array</span><span>(
            </span>'localhost',
            'root',
            'root',
            <span>array</span>(),  <span>//</span><span>为空备份全部数据库,否则备份这些数据库</span>
            'D:/xampp/mysql/bin/mysqldump',    <span>//</span><span>备份工具</span>
            <span>dirname</span>(<span>__FILE__</span>)."/localhost",  <span>//</span><span>目录加主机名</span>
            5,  <span>//</span><span>删除前5天的SQL文件</span>
        ),<span>);

    </span><span>foreach</span>(<span>$configs</span> <span>as</span> <span>$config</span><span>) {
        </span><span>$logsfile</span> = <span>$config</span>[5].'/'.<span>date</span>('ymd').'.log'<span>;
        logs(</span><span>$logsfile</span>, <span>$config</span>[0]." backup\n"<span>);
        backup(</span><span>$config</span><span>);
    }

    </span><span>function</span> backup(<span>$config</span><span>) {
        </span><span>list</span>(<span>$host</span>, <span>$username</span>, <span>$password</span>, <span>$databases</span>, <span>$backuptool</span>, <span>$backupdir</span>, <span>$day</span>) = <span>$config</span><span>;
        </span><span>$command</span> = "<span>$backuptool</span> -u <span>$username</span> -h <span>$host</span> -p<span>$password</span> %s > %s"<span>;  
        </span><span>$logsfile</span> = <span>$backupdir</span>.'/'.<span>date</span>('ymd').'.log'<span>;
        </span><span>$backfilename</span> = <span>$backupdir</span>.'/'.<span>date</span>('Ymd')."%s.sql";   <span>//</span><span>备份的SQL文件,以数据库命名</span>
        
        <span>if</span>(!<span>is_dir</span>(<span>$backupdir</span><span>)) {
            </span><span>mkdir</span>(<span>$backupdir</span>, 0755 , <span>true</span><span>); 
        }
        
        </span><span>//</span><span>删除前十天的备份文件</span>
        get_dir_files(<span>$backupdir</span>, <span>$returnval</span><span>);
        </span><span>if</span>(<span>$returnval</span><span>) {
            </span><span>foreach</span>(<span>$returnval</span> <span>as</span> <span>$v</span><span>) {
                </span><span>$time</span> = <span>filemtime</span>(<span>$v</span><span>);
                </span><span>if</span>(<span>$time</span> < <span>strtotime</span>("-<span>$day</span> day") && (<span>pathinfo</span>(<span>$v</span>,PATHINFO_EXTENSION))=='zip'<span>) {
                    </span><span>unlink</span>(<span>$v</span><span>);
                }
            }
        }
        
        </span><span>if</span>(!<span>$databases</span><span>) {
            </span><span>$databases</span> = getdatabases(<span>$host</span>, <span>$username</span>, <span>$password</span><span>);
        }

        </span><span>//</span><span>开始备份</span>
        <span>foreach</span>(<span>$databases</span> <span>as</span> <span>$database</span><span>) {
            </span><span>$outputfile</span> = <span>sprintf</span>(<span>$backfilename</span>, <span>$database</span><span>);
            </span><span>$execcommand</span> = <span>sprintf</span>(<span>$command</span>, <span>$database</span>, <span>$outputfile</span><span>);

            </span><span>try</span><span> {
                </span><span>if</span>(<span>system</span>(<span>$execcommand</span>) === <span>false</span><span>) {
                    </span><span>throw</span> <span>new</span> <span>Exception</span>('execute backup command error!'<span>);
                }
                
                </span><span>//</span><span>文件过大时会压缩失败(测试的那个SQL文件4.62G,压缩失败,没创建那个压缩文件。测试2.81G可以)</span>
                <span>if</span>(<span>file_exists</span>(<span>$outputfile</span><span>)) {
                    </span><span>$zip</span> = <span>new</span><span> ZipArchive();
                    </span><span>$filename</span> = <span>pathinfo</span>(<span>$outputfile</span>,<span>PATHINFO_FILENAME);
                    </span><span>$zipname</span> = <span>$backupdir</span>.'/'.<span>$filename</span>.'.zip';  <span>//</span><span>zip文件的路径</span>
                    <span>if</span>(<span>$zip</span>->open(<span>$zipname</span>, ZIPARCHIVE::OVERWRITE) === <span>true</span><span>) {
                        </span><span>$zip</span>->addFile(<span>$outputfile</span>, <span>$filename</span>.'.'.<span>pathinfo</span>(<span>$outputfile</span>,<span>PATHINFO_EXTENSION));
                        
                        </span><span>$zip</span>-><span>close();
                    }</span><span>else</span><span> {
                        </span><span>throw</span> <span>new</span> <span>Exception</span>('ZipArchive open error!'<span>);
                    }
                }
                
                </span><span>if</span>(!<span>file_exists</span>(<span>$zipname</span>) || (<span>filesize</span>(<span>$zipname</span>)==0<span>)) {
                    </span><span>throw</span> <span>new</span> <span>Exception</span>('ZipArchive create error!'<span>);
                }
                
                </span><span>$message</span> = <span>date</span>('Y-m-d H:i:s')."<span>$database</span> backup complete!\r\n"<span>;
                logs(</span><span>$logsfile</span>, <span>$message</span><span>);
            }</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>) {
                </span><span>$message</span> = <span>date</span>('Y-m-d H:i:s').<span>$e</span>->getLine().' '.<span>$e</span>->getMessage()."\r\n"<span>;
                logs(</span><span>$logsfile</span>, <span>$message</span><span>);
            }

        }
    }

    </span><span>function</span> getdatabases(<span>$host</span>, <span>$username</span>, <span>$password</span><span>) {
        </span><span>$databases</span> = <span>array</span><span>();
        
        </span><span>try</span><span> {
            </span><span>$mysqli</span> = <span>new</span> Mysqli(<span>$host</span>, <span>$username</span>, <span>$password</span><span>);
            </span><span>$result</span> = <span>$mysqli</span>->query("show databases"<span>);
            </span><span>if</span>(<span>$result</span><span>) {
                </span><span>while</span>(<span>$row</span> = <span>$result</span>-><span>fetch_row()) {
                    (</span><span>current</span>(<span>$row</span>)!='information_schema' && <span>current</span>(<span>$row</span>)!='mysql' && <span>current</span>(<span>$row</span>)!='performance_schema') && <span>$databases</span>[] = <span>current</span>(<span>$row</span><span>);
                }
                </span><span>$result</span>-><span>free_result();
                </span><span>$mysqli</span>-><span>close();
            }</span><span>else</span><span> {
                </span><span>throw</span> <span>new</span> <span>Exception</span>('No databases!'<span>);
            }
        }</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>) {
            </span><span>$message</span> = <span>date</span>('Y-m-d H:i:s').<span>$e</span>->getLine().' '.<span>$e</span>->getMessage()."\r\n"<span>;
            logs(</span><span>$logsfile</span>, <span>$message</span><span>);
        }    
        
        </span><span>return</span> <span>$databases</span><span>;
    }
    
    </span><span>function</span> logs(<span>$file</span>, <span>$contents</span><span>) {
        </span><span>$dirname</span> = <span>dirname</span>(<span>$file</span><span>);
        </span><span>try</span><span> {
            </span><span>if</span>(!<span>is_dir</span>(<span>dirname</span>(<span>$file</span>)) || !<span>is_writeable</span>(<span>dirname</span>(<span>$file</span><span>))) {
                </span><span>throw</span> <span>new</span> <span>Exception</span>("file is not direcotory or file can't write"<span>);
            }
            </span><span>file_put_contents</span>(<span>$file</span>, <span>$contents</span>,<span> FILE_APPEND);
        }</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>) {
            </span><span>$message</span> = <span>date</span>('Y-m-d H:i:s').<span>$e</span>->getLine.' '.<span>$e</span>->getMessage()."\r\n"<span>;
            logs(</span><span>$logfile</span>, <span>$message</span><span>);
        }
    }
    
    
    </span><span>//</span><span>获取当前目录下的文件(不包含子文件夹)</span>
    <span>function</span> get_dir_files(<span>$currPath</span>, &<span>$returnVal</span>=<span>array</span><span>()) {
        </span><span>if</span>(<span>is_dir</span>(<span>$currPath</span><span>)) {
            </span><span>$currPath</span> = (<span>substr</span>(<span>$currPath</span>,-1,1)=='/')?<span>substr</span>(<span>$currPath</span>,0,<span>strlen</span>(<span>$currPath</span>)-1):<span>$currPath</span><span>;

            </span><span>if</span>(<span>$handler</span> = <span>opendir</span>(<span>$currPath</span><span>)) {
                </span><span>while</span>((<span>$fileName</span> = <span>readdir</span>(<span>$handler</span>)) !== <span>false</span><span>) {
                    </span><span>if</span>(<span>$fileName</span> != '.' && <span>$fileName</span> != '..' && <span>$fileName</span>[0] != '.'<span>) {
                        </span><span>if</span>(<span>is_file</span>(<span>$currPath</span> . '/' . <span>$fileName</span><span>)) {
                            </span><span>$returnVal</span>[] = <span>$currPath</span> . '/' . <span>$fileName</span><span>;
                        }
                    }
                }
                </span><span>closedir</span>(<span>$handler</span><span>);
            }
        }
    }
</span>?>
Copy after login

mysqlbackup.bat:

D:xamppphpphp.exe -q D:wampwwwphp_libbasicmysqlbackup.php
pause;

Linux system shell backup MySQL:

#!/bin/<span>sh</span><span>
# </span><span>sed</span> -i <span>'</span><span>s/^M//g</span><span>'</span> /home/taskschd/backup.<span>sh</span><span>
#注意:</span>^M的输入方式是 Ctrl + v ,然后Ctrl +<span> M
dbs</span>=<span>(test)
ROOT_DIR</span>=/home/backup/
<span>for</span> dbname <span>in</span><span> ${dbs[@]}
 </span><span>do</span><span>
  #备份数据
  BACKUP_DIR</span>=$ROOT_DIR$dbname<span>'</span><span>_</span><span>'</span>$(<span>date</span> +%Y%m%<span>d).sql
  </span>/usr/local/mysql/bin/mysqldump --opt -uroot -pabc $dbname ><span> $BACKUP_DIR
  #删除三天前数据
  delete_file</span>=$dbname<span>'</span><span>_</span><span>'</span>$(<span>date</span> -d <span>"</span><span>-5 day</span><span>"</span> <span>"</span><span>+%Y%m%d</span><span>"</span>)<span>'</span><span>.sql</span><span>'</span>  
  <span>rm</span><span> $ROOT_DIR$delete_file  
 </span><span>done</span>
Copy after login

Another shell backup mysql script: http://www.cnblogs.com/luoyunshu/p/3435378.html

mySQL database backup under linux system Methods and scripts?

Method 1. Suitable for all formats of mysql database, write a script to export and import the database and execute it regularly:
1. Export the entire database mysqldump -u username -p database name> exported file name mysqldump - u wcnc -p smgp_apps_wcnc > /storage path/wcnc.sql
2. Export a table mysqldump -u username -p database name table name> exported file name mysqldump -u wcnc -p smgp_apps_wcnc users> /storage 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
Definition:
-d No data
--add-drop-table Add a drop table before each create statement
4. Import the common source command of the database into the mysql database console:
Such as mysql -u root -p mysql>use database

Method 2, for the mysql data table format is MyISAM
If the data file is in /var/lib/mysql
then write a script directly
cp -r /var/lib/mysql /Folder path to backup to

Use rsync incremental for offline backup, or scheduled full backup.

Who can give me a script for automatic backup of MYSQL

Maybe you don’t know how to use it

You can put this script into crontab and execute it once every morning for automatic backup

This script can only be executed once a day at most, and only the last five days of backup on the server.

Code:

#!/bin/bash
#This is a ShellScript For Auto DB Backup
#Powered by aspbiz
#2004-09

#Setting
#Set the database name, database login name, password, backup path, log path, data file location, and backup method
#The default backup method is tar, but it can also be mysqldump, mysqldotcopy
#By default, use root (empty) to log in to the mysql database and back up to /root/dbxxxxx.tgz
DBName=mysql
DBUser=root
DBPasswd=
BackupPath=/root/
LogFile=/root/db.log
DBPath=/var/lib/mysql/
#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 ]
then
rm -f $OldFile >> $LogFile 2>&1
echo " [$OldFile]Delete Old File Success!" >> $LogFile
else
echo "[$OldFile]No Old Backup File!" >> $LogFile
fi

if [ -f $NewFile ]
then
echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile
else
case $BackupMethod in
mysqldump)
if [ -z $DBPasswd ]
then
mysqldump -u $DBUser --opt $DBName > $DumpFile
else
mysqldump -u $DBUser -p $DBPasswd --opt $DBName > $DumpFile
f...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/834767.htmlTechArticleMySQL backup script, mysql script mysqlbackup.php: ? php // Backup mysql set_time_limit (0 ); date_default_timezone_set( ' PRC' ); // Configuration $configs = array ( 'host1'= array ( 'localh...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP development practice: Use PHPMailer to send emails to users in the MySQL database PHP development practice: Use PHPMailer to send emails to users in the MySQL database Aug 05, 2023 pm 06:21 PM

PHP development practice: Use PHPMailer to send emails to users in the MySQL database Introduction: In the construction of the modern Internet, email is an important communication tool. Whether it is user registration, password reset, or order confirmation in e-commerce, sending emails is an essential function. This article will introduce how to use PHPMailer to send emails and save the email information to the user information table in the MySQL database. 1. Install the PHPMailer library PHPMailer is

Go language and MySQL database: How to separate hot and cold data? Go language and MySQL database: How to separate hot and cold data? Jun 18, 2023 am 08:26 AM

As the amount of data continues to increase, database performance has become an increasingly important issue. Hot and cold data separation processing is an effective solution that can separate hot data and cold data, thereby improving system performance and efficiency. This article will introduce how to use Go language and MySQL database to separate hot and cold data. 1. What is hot and cold data separation processing? Hot and cold data separation processing is a way of classifying hot data and cold data. Hot data refers to data with high access frequency and high performance requirements. Cold data

How to use MySQL database for time series analysis? How to use MySQL database for time series analysis? Jul 12, 2023 am 08:39 AM

How to use MySQL database for time series analysis? Time series data refers to a collection of data arranged in time order, which has temporal continuity and correlation. Time series analysis is an important data analysis method that can be used to predict future trends, discover cyclical changes, detect outliers, etc. In this article, we will introduce how to use a MySQL database for time series analysis, along with code examples. Create a data table First, we need to create a data table to store time series data. Suppose we want to analyze the number

How to perform incremental data backup of MySQL database using Go language How to perform incremental data backup of MySQL database using Go language Jun 17, 2023 pm 02:28 PM

As the amount of data increases, database backup becomes more and more important. For the MySQL database, we can use the Go language to achieve automated incremental backup. This article will briefly introduce how to use Go language to perform incremental backup of MySQL database data. 1. Install the Go language environment. First, we need to install the Go language environment locally. You can go to the official website to download the corresponding installation package and install it. 2. Install the corresponding library. The Go language provides many third-party libraries for accessing MySQL databases, among which the most commonly used ones are

To what extent can I develop MySQL database skills to be successfully employed? To what extent can I develop MySQL database skills to be successfully employed? Sep 12, 2023 pm 06:42 PM

To what extent can I develop MySQL database skills to be successfully employed? With the rapid development of the information age, database management systems have become an indispensable and important component in all walks of life. As a commonly used relational database management system, MySQL has a wide range of application fields and employment opportunities. So, to what extent do MySQL database skills need to be developed to be successfully employed? First of all, mastering the basic principles and basic knowledge of MySQL is the most basic requirement. MySQL is an open source relational database management

How to use MySQL database for image processing? How to use MySQL database for image processing? Jul 14, 2023 pm 12:21 PM

How to use MySQL database for image processing? MySQL is a powerful relational database management system. In addition to storing and managing data, it can also be used for image processing. This article will introduce how to use a MySQL database for image processing and provide some code examples. Before you begin, make sure you have installed a MySQL database and are familiar with basic SQL statements. Create a database table First, create a new database table to store the image data. The structure of the table can be as follows

How to make reliable MySQL database connection using Go language? How to make reliable MySQL database connection using Go language? Jun 17, 2023 pm 07:18 PM

With the large amount of data that needs to be stored and processed, MySQL has become one of the most commonly used relational databases in application development. The Go language is becoming more and more popular among developers due to its efficient concurrency processing and concise syntax. This article will lead readers to implement reliable MySQL database connection through Go language, allowing developers to query and store data more efficiently. 1. Several ways for Go language to connect to MySQL database. There are usually three ways to connect to MySQL database in Go language, which are: 1. Third-party library

MySQL database and Go language: How to perform data caching? MySQL database and Go language: How to perform data caching? Jun 17, 2023 am 10:05 AM

In recent years, the Go language has become increasingly popular among developers and has become one of the preferred languages ​​for developing high-performance web applications. MySQL is also a popular database that is widely used. In the process of combining these two technologies, caching is a very important part. The following will introduce how to use Go language to handle the cache of MySQL database. The concept of caching In web applications, caching is a middle layer created to speed up data access. It is mainly used to store frequently requested data to

See all articles