首页 > 开发 > PHP > 正文

一段导出数据库的代码

2024-05-04 22:58:59
字体:
来源:转载
供稿:网友

一段导出数据库的代码
 <?
//
$dbname="mytest";
$filename="file.sql";
mysql_pconnect ("localhost:3306","root","");
//
function sqldumptable($table) {
global $db_site;
$tabledump = "drop table if exists $table;/n";
$tabledump .= "create table $table (/n";
$firstfield=1;
$fields = mysql_query("show fields from $table");
while ($field = mysql_fetch_array($fields)) {
if (!$firstfield) {$tabledump .= ",/n";} else {$firstfield=0;}
$tabledump .= " $field[field] $field[type]";
if (!empty($field["default"])) {$tabledump .= " default '$field[default]'";}
if ($field[null] != "yes") {$tabledump .= " not null";}
if ($field[extra] != "") {$tabledump .= " $field[extra]";}
}
mysql_free_result($fields);
$keys = mysql_query("show keys from $table");
while ($key = mysql_fetch_array($keys)) {
$kname=$key['key_name'];
if ($kname != "primary" and $key['non_unique'] == 0) { $kname="unique|$kname";}
if(!is_array($index[$kname])) { $index[$kname] = array();}
$index[$kname][] = $key['column_name'];
}
mysql_free_result($keys);

// get each key info
while(list($kname, $columns) = @each($index)){
$tabledump .= ",/n";
$colnames=implode($columns,",");

if($kname == "primary"){ $tabledump .= " primary key ($colnames)";}
else {
if (substr($kname,0,6) == "unique") {
// key is unique
$kname=substr($kname,7);
}

$tabledump .= " key $kname ($colnames)";

}
}

$tabledump .= "/n);/n/n";

// get data
$rows = mysql_query("select * from $table");
$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 .= "'".addslashes($row[$fieldcounter])."'";
}
}

$tabledump .= ");/n";
}
mysql_free_result($rows);

return $tabledump;
}
//函数结束
//
$result = mysql_list_tables ($dbname);
$i = 0;
while ($i < mysql_num_rows ($result)) {
$tb_names[$i] = mysql_tablename ($result, $i);
$dump.=sqldumptable($tb_names[$i])."/n/n/n";
$i++;
}

echo $dump;//可以在浏览器里输出看看
$filehandle=fopen($filename,"w");
fwrite($filehandle,$dump."/n/n/n");
fclose($filehandle);

echo "<p>数据成功导出!</p>";
?>
把$filename="file.sql";改成$filename="file.txt";
 
 

注册会员,创建你的web开发资料库,
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表