Home > Backend Development > PHP Tutorial > PHP export .sql file/mysql database backup program_PHP tutorial

PHP export .sql file/mysql database backup program_PHP tutorial

WBOY
Release: 2016-07-13 17:04:08
Original
1284 people have browsed it

php tutorial export .sql file/mysql tutorial database tutorial backup program

$database='';//Database name
$options=array(
'hostname' => '',//ip address
'charset' => 'utf8',//encoding
'filename' => $database.'.sql',//File name
'username' => '',
'password' => ''
);
mysql_connect($options['hostname'],$options['username'],$options['password'])or die("Cannot connect to database!");
mysql_select_db($database) or die("Wrong database name!");
mysql_query("SET NAMES '{$options['charset']}'");
$tables = list_tables($database);
$filename = sprintf($options['filename'],$database);
$fp = fopen($filename, 'w');
foreach ($tables as $table) {
​ dump_table($table, $fp);
}
fclose($fp);
//Download sql file
$file_name=$options['filename'];
Header("Content-type:application/octet-stream");
Header("Content-Disposition:attachment;filename=".$file_name);
readfile($file_name);
//Delete the sql file on the server
unlink($file_name);
exit;
//Get the name of the table
function list_tables($database)
{
$rs = mysql_list_tables($database);
$tables = array();
While ($row = mysql_fetch_row($rs)) {
          $tables[] = $row[0];
}
Mysql_free_result($rs);
Return $tables;
}
//Export database
function dump_table($table, $fp = null)
{
$need_close = false;
If (is_null($fp)) {
           $fp = fopen($table . '.sql', 'w');
         $need_close = true;
}
$a=mysql_query("show create table `{$table}`");
$row=mysql_fetch_assoc($a);fwrite($fp,$row['Create Table'].';');//Export table structure
$rs = mysql_query("SELECT * FROM `{$table}`");
While ($row = mysql_fetch_row($rs)) {
            fwrite($fp, get_insert_sql($table, $row));
}
Mysql_free_result($rs);
If ($need_close) {
            fclose($fp);
}
}
//Export table data
function get_insert_sql($table, $row)
{
$sql = "INSERT INTO `{$table}` VALUES (";
$values ​​= array();
foreach ($row as $value) {
          $values[] = "'" . mysql_real_escape_string($value) . "'";
}
$sql .= implode(', ', $values) . ");";
Return $sql;
}?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630883.htmlTechArticlephp tutorial export .sql file/mysql tutorial database tutorial backup procedure?php $database='';//database Name $options=array( 'hostname' = '',//ip address 'charset' = 'utf8',//encoding 'filename'...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template