function sqldumptable($table, $fp=0) {
$tabledump = "DROP TABLE IF EXISTS $table;\\n";
$tabledump .= "CREATE TABLE $table (\\n";
$firstfield=1;
// get columns and spec
$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"])) {
// get default value
$tabledump .= " DEFAULT ''$field[Default]''";
}
if ($field[''Null''] != "YES") {
// can field be null
$tabledump .= " NOT NULL";
}
if ($field[''Extra''] != "") {
// any extra info?
$tabledump .= " $field[Extra]";
}
}
mysql_free_result($fields
// get keys list
$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") {
// do primary key
$tabledump .= " PRIMARY KEY ($colnames)";
} else {
// do standard key
if (substr($kname,0,6) == "UNIQUE") {
// key is unique
$kname=substr($kname,7
}
$tabledump .= " KEY $kname ($colnames)";
}
}
$tabledump .= "\\n
\\n\\n";
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
}
//backup
//这是一个备份数据库中所以表的循环
/*if ($_POST[action]=="dobackup") {
$table = array_flip($_POST[table]
$filehandle = fopen($path,"w"
$result = $DB->query("SHOW tables"
while ($currow = $DB->fetch_array($result)) {
if (isset($table[$currow[0]])) {
sqldumptable($currow[0], $filehandle
fwrite($filehandle,"\\n\\n\\n"
}
}
fclose($filehandle
pa_exit("数据库已备份"
}
*/
//这是备份一个表"a"
$filehandle = fopen($path,"w")
sqldumptable("a", $filehandle)
fclose($filehandle)