yeah

搜索

计数器

62789

链接

备份,恢复数据库

Dec 23, 2009 10:53:21 PM | Comments(1) | Category:PHP学习 | Tags:

 

<?php
 



/*备份数据库,参数$tables如果手工设定地话,不需要给出表前缀
 $dbname 数据库名字
 $bakfile可以不指定(备份在PHP程序同一目录下),
 也可以是一个目录(自动生成个文件名备份在此目录下),也可以是一个包含路径的文件名
 */

 public function backup($bakupFile = null, $tables = array())
 {
  if (empty($bakupFile)) {
   $backupFile = $this->dbname . date("Ymdhis") . '.sql';
  } elseif (is_dir($backupFile)) { //判断$backupFile是否为目录
   if (preg_match('/\/$/', $backupFile)) { //如果$backupFile 的格式为 "目录名/"
    $backupFile = $backupFile . $this->dbname . date("Ymdhis") . '.sql';
   } else {
    $backupFile = $backupFile . '/' . $this->dbname . date("Ymdhis") . '.sql';
   }
  }
  if (!$tables) { //如果数组 $tables为空,则备份所有表
   $this->query("SHOW TABLES");
   while ($row = mysql_fetch_row($this->queryID)) {
    $tables[] = $row[0];
   }
  } else {
   foreach ($tables as $k => $v) {
    $tables[$k] = $this->tablePrefix . $v;
   }
  }
 
  if ($fp = fopen($bakfile, 'wb')) {
   if ($this->dbcharset) { //是否设置了数据库的编码格式
    fwrite($fp, "SET NAMES " . $this->dbcharset . ";\n\n");
   }
   foreach ($tables as $table) {
    $this->dumpTable($table, $fp); //备份表
    fwrite($fp, "\n");
   }//foreach
   fclose($fp);
   return true;
  } else {
   return false;
  }//if
 }
 
 //私有方法 导出表格
 protected function dumpTable($table, $fp)
 {
  //备份表结构
  //fwrite($fp, "-- \n-- {$table}\n-- \n");
  $row = $this->findBySql("SHOW CREATE TABLE `{$table}`");
  fwrite($fp, str_replace("\n","", $row['Create Table']) . ";\n\n" );
  //备份表数据
  $this->query("SELECT * FROM `{$table}`");
  while ($row = mysql_fetch_assoc($this->queryID)) {
   foreach ($row as $k=>$v) {
    $row[$k] = "'" . $this->qstr($v) . "'" ; //用mysql_real_escape_string 转义字符
   }
   $sql = "INSERT INTO `$table` VALUES (" . join(",", $row) . ");\n";
   fwrite($fp, $sql);
  }
  mysql_free_result($this->queryID);
  fwrite($fp, "\n");
 }
 
 //恢复数据库文件
 public function restore($bakfile)
 {
  if ($fp = fopen($bakfile, 'r')) {
   $sql = '';
   while (!feof($fp)) {
    $line = fgets($fp);
    if (strpos($line,'--')!==0)
    {
     $sql .= $line;
     //pp($sql);
    }
    if (preg_match('/;\s*$/', $sql)) {
     $this->query($sql);
     $sql = '';
    }
   }
   fclose($fp);
   return true;
  } else {
   return false;
  }
 }
 
?>