<?php
$link = mysql_connect(DB_HOST,DB_USER,DB_PASS);
$tables = mysql_list_tables(DB_NAME);
$cachetables = array(); $tableselected = array();
while ($table = mysql_fetch_row($tables))
{
$cachetables[$table[0]] = $table[0];
$tableselected[$table[0]] = 1;
}
$table = $cachetables;
$filename = DB_NAME . "_" . date("Y_m_d_H_i_s") . ".sql";
$path = "sql/" . $filename;
$filehandle = fopen($path, "w");
$result = mysql_query("SHOW tables");
while ($currow = mysql_fetch_array($result))
{
if (isset($table[$currow[0]]))
{
sqldumptable($currow[0], $filehandle);
fwrite($filehandle, "nnn");
}
}
fclose($filehandle);
$update_data = array('filename' => $filename, 'postdate' => mktime());
$db->insert('backup_db', $update_data);
// data dump functions
function sqldumptable($table, $fp = 0)
{
$tabledump = "DROP TABLE IF EXISTS " . $table . ";n";
$result = mysql_fetch_array(mysql_query("SHOW CREATE TABLE " . $table));
//echo "SHOW CREATE TABLE $table";
$tabledump .= $result[1] . ";rn";
if ($fp) {
fwrite($fp, $tabledump);
} else {
echo $tabledump;
}
// get data
$rows = mysql_query("SELECT * FROM " . $table);
// $numfields=$DB->num_fields($rows);
$numfields = mysql_num_fields($rows);
while ($row = mysql_fetch_array($rows)) {
$tabledump = "INSERT INTO " . $table . " VALUES(";
$fieldcounter = -1;
$firstfield = 1;
// get each field's data
while (++$fieldcounter < $numfields) {
if (!$firstfield) {
$tabledump .= ", ";
} else {
$firstfield = 0;
}
if (!isset($row[$fieldcounter])) {
$tabledump .= "NULL";
} else {
$tabledump .= "'" . mysql_escape_string($row[$fieldcounter]) . "'";
}
}
$tabledump .= ");n";
if ($fp) {
fwrite($fp, $tabledump);
} else {
echo $tabledump;
}
}
mysql_free_result($rows);
}
3、导入数据库
<?php
/************
*
PHP导入.sql文件
运行版本:php5,php4 使用的时候请选择
link:http://www.jb200.com
*
*************/
$file_dir = dirname(__FILE__);
$file_name = "2010-05-09-bak.sql";
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME, $conn);
/** PHP5 版本 **/
$get_sql_data = file_get_contents($file_name, $file_dir);
/**
* PHP4 版本
if(file_exists($file_dir."/".$file_name))
{
$get_sql_data = fopen($file_dir."/".$file_name,"r");
if(!$get_sql_data)
{
echo "不能打开文件";
}
else
{
$get_sql_data = fread($get_sql_data, filesize ($file_dir."/".$file_name));
}
}
***/
$explode = explode(";", $get_sql_data);
$cnt = count($explode);
for ($i=0; $i<$cnt; $i++)
{
$sql = $explode[$i];
$result = mysql_query($sql);
mysql_query("set names 'utf8'");
if ($result) {
echo "成功:".$i."个查询<br>";
} else {
echo "导入失败:".mysql_error();
}
}
?>
您可能感兴趣的文章:
php数据库备份类 分享一个不错的php数据库备份类
php完整备份数据库与备份数据库中指定表的类
php Mysql数据库备份类及调用方法
php实现mysql的备份与还原实例代码
php实现MYSQL的备份与还原
php mysql备份的代码(xml应用)