search
HomeDatabaseSQLWhat are the two methods of database backup?

What are the two methods of database backup?

Jun 14, 2019 am 11:02 AM
backupdatabase

数据库备份的两种方法是:1、使用mysqldump结合exec函数进行数据库备份;2、使用【php+mysql+header】函数进行数据库备份。

What are the two methods of database backup?

数据库备份是必要的一般都是使用mysqldump进行备份,我这边写了两种备份方法可以参考一下。

第一种:使用mysqldump结合exec函数进行数据库备份操作。

代码如下:

/**
 * Subject: php-mysql 实现数据库备份.
 * User: luokakale
 * Date: 2018/11/9
 * Time: 13:31
 */

header('Content-Type:text/html;charset=utf8');
ini_set("max_execution_time", "0");//代码运行时间不限制  防止备份失败
ini_set('memory_limit', '128M');//设置内存 根据需求可以修改
date_default_timezone_set("PRC");
//创建需要保存sql文件的文件夹
$path = 'D:\SQL\databse_backup';
//定义数据库配置
$user = ''; //数据库账户
$pwd  = ''; //数据库密码
$dbname = ''; //数据库名称

//备份数据库命令地址文件
$sqladdress = 'D:\phpStudy\MySQL\bin\mysqldump.exe';

//备份指定地址
$time = time();
$path = 'D:\SQL\databse_backup'.'\\'.date("Ymd",$time);
if(!file_exists($path))
{
    mkdir($path,0777,true);
}

//备份的数据库文件名
$sqlFile = $dbname."_%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%.sql";
//判断是否存在密码
$password = $pwd== ''?'':'  -p'.$pwd;
//拼接备份命令
$order =  $sqladdress.' --opt  -u'.$user.$password.' '.$dbname.' >'.$path.'\\'.$sqlFile;
//执行命令
exec($order);

我使用的是集成的phpstudy里面的mysql下面的mysqldump.exe来备份,备份的数据库名字写法是 数据库名字+年月日时.  上面代码中我对数据库密码进行了判断,我这边有些数据库是不需要密码的。最后使用exec执行命令。

第二种:使用php+mysql+header函数进行数据库备份和下载操作。

代码如下:

header('Content-Type:text/html;charset=utf8');
ini_set("max_execution_time", "0");//代码运行时间不限制  防止备份失败
ini_set('memory_limit', '1024M');//设置内存 根据需求可以修改
date_default_timezone_set("PRC");
header("Content-Type:text/html;charset=utf-8");
$host="";
$user="";//账户
$password="";//密码
$dbname="";//数据库名称
$con =  mysqli_connect("$host","$user","$password","$dbname");
mysqli_select_db($con,$dbname);
$mysql= "set charset utf8;\r\n";#for mysql>=5.0
mysqli_query($con,"SET NAMES 'UTF8'");
$q1=mysqli_query($con,"show tables");
while($t=mysqli_fetch_array($q1)){
    $table=$t[0];
    $q2=mysqli_query($con,"show create table `$table`");
    $sql=mysqli_fetch_array($q2);
    $mysql.=$sql['Create Table'].";\r\n\r\n";#DDL
    $q3=mysqli_query($con,"select * from `$table`");
    while($data=mysqli_fetch_assoc($q3))
    {
        $keys=array_keys($data);
        $keys=array_map('addslashes',$keys);
        $keys=join('`,`',$keys);
        $keys="`".$keys."`";
        $vals=array_values($data);
        $vals=array_map('addslashes',$vals);
        $vals=join("','",$vals);
        $vals="'".$vals."'";
        $mysql.="insert into `$table`($keys) values($vals);\r\n";
        unset($data);
    }
    $mysql.="\r\n";
    unset($t);
}
mysqli_close($con);
$filename=date('Ymj').".sql"; //文件名为当天的日期
$time = time();
$path = 'D:\SQL\databse_backup'.'\\'.date("Ymd",$time).'\\';
// 检查目录是否存在
if(!is_dir($path)){
    // 新建目录
    mkdir($path, 0777, true);
}
$file_name = $path.$filename;
$fp = fopen($file_name,'w');
fputs($fp,$mysql);
fclose($fp);
$fp=fopen($file_name,"r");
$file_size=filesize($file_name);
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".$file_size);
header("Content-Disposition: attachment; filename=".$filename);
//这里一定要使用echo 进行输出,否则下载的文家是空白的
echo fread($fp,$file_size);
fclose($fp);
exit;

个人建议用第一种,第二种太消耗内存了。

第一种可以做成定时备份,windows下可以用定时任务。

更多SQL的相关技术文章,请访问SQL教程栏目进行学习!

The above is the detailed content of What are the two methods of database backup?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
SQL and Databases: A Perfect PartnershipSQL and Databases: A Perfect PartnershipApr 25, 2025 am 12:04 AM

The relationship between SQL and database is closely integrated, and SQL is a tool for managing and operating databases. 1.SQL is a declarative language used for data definition, operation, query and control. 2. The database engine parses SQL statements and executes query plans. 3. Basic usage includes creating tables, inserting and querying data. 4. Advanced usage involves complex queries and subqueries. 5. Common errors include syntax, logic and performance issues, which can be debugged through syntax checking and EXPLAIN commands. 6. Optimization techniques include using indexes, avoiding full table scanning and optimizing queries.

SQL vs. MySQL: Clarifying the Relationship Between the TwoSQL vs. MySQL: Clarifying the Relationship Between the TwoApr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

The Importance of SQL: Data Management in the Digital AgeThe Importance of SQL: Data Management in the Digital AgeApr 23, 2025 am 12:01 AM

SQL's role in data management is to efficiently process and analyze data through query, insert, update and delete operations. 1.SQL is a declarative language that allows users to talk to databases in a structured way. 2. Usage examples include basic SELECT queries and advanced JOIN operations. 3. Common errors such as forgetting the WHERE clause or misusing JOIN, you can debug through the EXPLAIN command. 4. Performance optimization involves the use of indexes and following best practices such as code readability and maintainability.

Getting Started with SQL: Essential Concepts and SkillsGetting Started with SQL: Essential Concepts and SkillsApr 22, 2025 am 12:01 AM

SQL is a language used to manage and operate relational databases. 1. Create a table: Use CREATETABLE statements, such as CREATETABLEusers(idINTPRIMARYKEY, nameVARCHAR(100), emailVARCHAR(100)); 2. Insert, update, and delete data: Use INSERTINTO, UPDATE, DELETE statements, such as INSERTINTOusers(id, name, email)VALUES(1,'JohnDoe','john@example.com'); 3. Query data: Use SELECT statements, such as SELEC

SQL: The Language, MySQL: The Database Management SystemSQL: The Language, MySQL: The Database Management SystemApr 21, 2025 am 12:05 AM

The relationship between SQL and MySQL is: SQL is a language used to manage and operate databases, while MySQL is a database management system that supports SQL. 1.SQL allows CRUD operations and advanced queries of data. 2.MySQL provides indexing, transactions and locking mechanisms to improve performance and security. 3. Optimizing MySQL performance requires attention to query optimization, database design and monitoring and maintenance.

What SQL Does: Managing and Manipulating DataWhat SQL Does: Managing and Manipulating DataApr 20, 2025 am 12:02 AM

SQL is used for database management and data operations, and its core functions include CRUD operations, complex queries and optimization strategies. 1) CRUD operation: Use INSERTINTO to create data, SELECT reads data, UPDATE updates data, and DELETE deletes data. 2) Complex query: Process complex data through GROUPBY and HAVING clauses. 3) Optimization strategy: Use indexes, avoid full table scanning, optimize JOIN operations and paging queries to improve performance.

SQL: A Beginner-Friendly Approach to Data Management?SQL: A Beginner-Friendly Approach to Data Management?Apr 19, 2025 am 12:12 AM

SQL is suitable for beginners because it is simple in syntax, powerful in function, and widely used in database systems. 1.SQL is used to manage relational databases and organize data through tables. 2. Basic operations include creating, inserting, querying, updating and deleting data. 3. Advanced usage such as JOIN, subquery and window functions enhance data analysis capabilities. 4. Common errors include syntax, logic and performance issues, which can be solved through inspection and optimization. 5. Performance optimization suggestions include using indexes, avoiding SELECT*, using EXPLAIN to analyze queries, normalizing databases, and improving code readability.

SQL in Action: Real-World Examples and Use CasesSQL in Action: Real-World Examples and Use CasesApr 18, 2025 am 12:13 AM

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function