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 . ";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; } }
教程地址:http://www.phprm.com/code/4ed177caeff3321f45b6df6961c58565.html
欢迎转载!但请带上文章地址^^