当前位置:编程学习 > php >>

php数据库备份程序

php数据库备份程序

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 . ";\n\n");
   }
   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'] . ";\n\n" );
  //备份表库数据
  $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;
  }
 }

补充:Php教程,Php常用代码 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,