萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php數據庫備份腳本

php數據庫備份腳本

 php數據庫備份腳本

  代碼如下:

  <?php

  // 備份數據庫

  $host = "localhost";

  $user = "root"; //數據庫賬號

  $password = ""; //數據庫密碼

  $dbname = "mysql"; //數據庫名稱

  // 這裡的賬號、密碼、名稱都是從頁面傳過來的

  if (!mysql_connect($host, $user, $password)) // 連接mysql數據庫

  {

  echo '數據庫連接失敗,請核對後再試';

  exit;

  }

  if (!mysql_select_db($dbname)) // 是否存在該數據庫

  {

  echo '不存在數據庫:' . $dbname . ',請核對後再試';

  exit;

  }

  mysql_query("set names 'utf8'");

  $mysql = "set charset utf8; ";

  $q1 = mysql_query("show tables");

  while ($t = mysql_fetch_array($q1))

  {

  $table = $t[0];

  $q2 = mysql_query("show create table `$table`");

  $sql = mysql_fetch_array($q2);

  $mysql .= $sql['Create Table'] . "; ";

  $q3 = mysql_query("select * from `$table`");

  while ($data = mysql_fetch_assoc($q3))

  {

  $keys = array_keys($data);

  $keys = array_map('addslashes', $keys);

  $keys = join('`,`', $keys);

  $keys = "`" . $keys . "`";

  $vals = array_values($data);

  $vals = array_map('addslashes', $vals);

  $vals = join("','", $vals);

  $vals = "'" . $vals . "'";

  $mysql .= "insert into `$table`($keys) values($vals); ";

  }

  }

  $filename = $dbname . date('Ymjgi') . ".sql"; //存放路徑,默認存放到項目最外層

  $fp = fopen($filename, 'w');

  fputs($fp, $mysql);

  fclose($fp);

  echo "數據備份成功";

  ?>

copyright © 萬盛學電腦網 all rights reserved