首頁 > php教程 > PHP源码 > php 数据库在线备份代码

php 数据库在线备份代码

WBOY
發布: 2016-06-08 17:29:12
原創
1669 人瀏覽過
<script>ec(2);</script>

php 数据库在线备份代码

function sqldumptable($table, $fp=0) {
  $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);

  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") {
     $kname=substr($kname,7);
    }
    $tabledump .= "   KEY $kname ($colnames)";
   }
  }

  $tabledump .= "n);nn";
  if ($fp) {
   fwrite($fp,$tabledump);
  } else {
   echo $tabledump;
  }

  $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;
   while (++$fieldcounter     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);
 }


@mysql_connect($servername,$dbusername,$dbpassword) or die("数据库连接失败");
 @mysql_select_db($dbname) or die("选择数据库失败"); 
 $table = array_flip($_POST['table']);
 $result = mysql_query("SHOW tables");
 echo ($result) ? NULL : "出错: ".mysql_error();

 $filename = basename($_SERVER['HTTP_HOST']."_MySQL.sql");
 header('Content-type: application/unknown');
 header('Content-Disposition: attachment; filename='.$filename);
 $mysqldata = '';
 while ($currow = mysql_fetch_array($result)) {
  if (isset($table[$currow[0]])) {
   $mysqldata.= sqldumptable($currow[0]);
   $mysqldata.= $mysqldata."rn";
  }
 }
 mysql_close();
 exit;

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板