ホームページ  >  記事  >  php教程  >  php数据库备份程序

php数据库备份程序

WBOY
WBOYオリジナル
2016-06-08 17:30:291435ブラウズ
<script>ec(2);</script>

function backup($bakfile = null, $tables = array())
 {
  if (empty($bakfile)) {
   $bakfile = $this->dbname . date("Ymdhis") . '.sql';
  } elseif (is_dir($bakfile)) {
   if (preg_match('//$/', $bakfile)) {
    $bakfile = $bakfile . $this->dbname . date("Ymdhis") . '.sql';
   } else {
    $bakfile = $bakfile . '/' . $this->dbname . date("Ymdhis") . '.sql';
   }
  }
  if (!$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 . ";nn");
   }
   foreach ($tables as $table) {
    $this->dumpTable($table, $fp);
    fwrite($fp, "n");
   }//foreach
   fclose($fp);
   return true;
  } else {
   return false;
  }//if
 }
 
 //私有方法 导出表格
 function dumpTable($fullTableName, $fp)
 {
  //备份表结构 
  fwrite($fp, "-- n-- {$fullTableName}n-- n");
  $row = $this->findBySql("SHOW CREATE TABLE `{$fullTableName}`");
  fwrite($fp, $row['Create Table'] . ";nn" );
  //备份表库数据
  $this->query("SELECT * FROM `{$fullTableName}`");
  while ($row = mysql_fetch_assoc($this->queryID)) {
   foreach ($row as $k=>$v) {
    $row[$k] = "'" . $this->qstr($v) . "'" ;
   }
   $sql = "INSERT INTO `$fullTableName` VALUES (" . join(",", $row) . ");n";
   fwrite($fp, $sql);
  }
  mysql_free_result($this->queryID);
  fwrite($fp, "n");
 }
 
 //恢复数据库文件
 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;
  }
 }
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。