Home > Article > Backend Development > How to implement automatic database backup in PHP
mysqldump -u username -p dbname table1 table2 ... > BackupName.sql
##2.5, substr
2.6, fwrite
3. Implementation ideas
4. Code composition
/** * [copyDb description] 备份数据库 * @param [type] $dbname [description] 数据库名 * @param [type] $fileName [description] 存储的文件名 * @return [type] [description] */public function copyDb($dbname, $fileName){ $myfile = fopen($fileName, "w") or die("Unable to open file!");//打开存储文件 $this->link->query("use {$dbname}");//切换数据库 $this->changeDb($dbname); $tables = $this->link->query('show tables');//获取当期数据库所有表名称 while($re = $tables->fetch(PDO::FETCH_ASSOC)){ //var_dump($re);//查看数组构成 $tableName = $re['Tables_in_'.$dbname];//构成特定的下标 $sql = "show create table {$tableName};"; $tableSql = $this->link->query($sql); fwrite($myfile, "DROP TABLE IF EXISTS `{$tableName}`;\r\n");//加入默认删除表的遇见 //下面备份表结构,这个循环之执行一次 while($re = $tableSql->fetch(PDO::FETCH_ASSOC)){ // echo "<pre class="brush:php;toolbar:false">"; // var_dump($re); // echo ""; echo "正在备份表{$re['Table']}结构
5. Conclusion
The main process of backing up the database:
1: Switch to the corresponding database;
2: Use show create table tableName to obtain the table structure and write it to the file;
3: Then query all table data, loop to generate the corresponding sql statement, and write it to the file;
4: The sql file generated by trial run;
The above is the detailed content of How to implement automatic database backup in PHP. For more information, please follow other related articles on the PHP Chinese website!