下面是一個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;/r/n";
- $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'] . ";/r/n";
- $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);/r/n";
- }
- }
- $filename = $dbname . date('Ymjgi') . ".sql"; //存放路徑,默認存放到項目最外層
- $fp = fopen($filename, 'w');
- fputs($fp, $mysql);
- fclose($fp);
- echo "數據備份成功";
- ?>
如果使用的是thinkphp可以使用下面代碼來備份mysql數據庫
- <?php
- // m.survivalescaperooms.com
- class BaksqlAction extends CommonAction {
- public $config = ''; //相關配置
- public $model = ''; //實例化一個model
- public $content; //內容
- public $dbName = ''; //數據庫名
- public $dir_sep = '/'; //路徑符號
- //初始化數據
- function _initialize() {
- parent::_initialize();
- header("Content-type: text/html;charset=utf-8");
- set_time_limit(0); //不超時
- ini_set('memory_limit','500M');
- $this->config = array(
- 'path' => C('DB_BACKUP'), //備份文件存在哪里
- 'isCompress' => 0, //是否開啟gzip壓縮 【未測試】
- 'isDownload' => 0 //備份完成后是否下載文件 【未測試】
- );
- $this->dbName = C('DB_NAME'); //當前數據庫名稱
- $this->model = new Model();
- //$sql = 'set interactive_timeout=24*3600'; //空閑多少秒后 斷開鏈接
- //$this->model>execute($sql);
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 已備份數據列表
- * +------------------------------------------------------------------------
- */
- function index() {
- $path = $this->config['path'];
- $fileArr = $this->MyScandir($path);
- foreach ($fileArr as $key => $value) {
- if ($key > 1) {
- //獲取文件創建時間
- $fileTime = date('Y-m-d H:i:s', filemtime($path . '/' . $value));
- $fileSize = filesize($path . '/' . $value) / 1024;
- //獲取文件大小
- $fileSize = $fileSize < 1024 ? number_format($fileSize, 2) . ' KB' :
- number_format($fileSize / 1024, 2) . ' MB';
- //構建列表數組
- $list[] = array(
- 'name' => $value,
- 'time' => $fileTime,
- 'size' => $fileSize
- );
- }
- }
- $this->assign('list', $list);
- $this->display();
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 獲取數據表
- * +------------------------------------------------------------------------
- */
- function tablist() {
- $list = $this->model->query("SHOW TABLE STATUS FROM {$this->dbName}"); //得到表的信息
- //echo $Backup->getLastSql();
- $this->assign('list', $list);
- $this->display();
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 備份整個數據庫
- * +------------------------------------------------------------------------
- */
- function backall() {
- $tables = $this->getTables();
- if ($this->backup($tables)) {
- $this->success('數據庫備份成功!', '/public/ok');
- } else {
- $this->error('數據庫備份失敗!');
- }
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 按表備份,可批量
- * +------------------------------------------------------------------------
- */
- function backtables() {
- $tab = $_REQUEST['tab'];
- if (is_array($tab))
- $tables = $tab;
- else
- $tables[] = $tab;
- if ($this->backup($tables)) {
- if (is_array($tab))
- $this->success('數據庫備份成功!');
- else
- $this->success('數據庫備份成功!', '/public/ok');
- } else {
- $this->error('數據庫備份失敗!');
- }
- }
- //還原數據庫
- function recover() {
- if ($this->recover_file($_GET['file'])) {
- $this->success('數據還原成功!', '/public/ok');
- } else {
- $this->error('數據還原失敗!');
- }
- }
- //刪除數據備份
- function deletebak() {
- if (unlink($this->config['path'] . $this->dir_sep . $_GET['file'])) {
- $this->success('刪除備份成功!', '/public/ok');
- } else {
- $this->error('刪除備份失敗!');
- }
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 下載備份文件
- * +------------------------------------------------------------------------
- */
- function downloadBak() {
- $file_name = $_GET['file'];
- $file_dir = $this->config['path'];
- if (!file_exists($file_dir . "/" . $file_name)) { //檢查文件是否存在
- return false;
- exit;
- } else {
- $file = fopen($file_dir . "/" . $file_name, "r"); // 打開文件
- // 輸入文件標簽
- header('Content-Encoding: none');
- header("Content-type: application/octet-stream");
- header("Accept-Ranges: bytes");
- header("Accept-Length: " . filesize($file_dir . "/" . $file_name));
- header('Content-Transfer-Encoding: binary');
- header("Content-Disposition: attachment; filename=" . $file_name); //以真實文件名提供給瀏覽器下載
- header('Pragma: no-cache');
- header('Expires: 0');
- //輸出文件內容
- echo fread($file, filesize($file_dir . "/" . $file_name));
- fclose($file);
- exit;
- }
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 獲取 目錄下文件數組
- * +------------------------------------------------------------------------
- * * @ $FilePath 目錄路徑
- * * @ $Order 排序
- * +------------------------------------------------------------------------
- * * @ 獲取指定目錄下的文件列表,返回數組
- * +------------------------------------------------------------------------
- */
- private function MyScandir($FilePath = './', $Order = 0) {
- $FilePath = opendir($FilePath);
- while ($filename = readdir($FilePath)) {
- $fileArr[] = $filename;
- }
- $Order == 0 ? sort($fileArr) : rsort($fileArr);
- return $fileArr;
- }
- /* * ******************************************************************************************** */
- /* -
- * +------------------------------------------------------------------------
- * * @ 讀取備份文件
- * +------------------------------------------------------------------------
- * * @ $fileName 文件名
- * +------------------------------------------------------------------------
- */
- private function getFile($fileName) {
- $this->content = '';
- $fileName = $this->trimPath($this->config['path'] . $this->dir_sep . $fileName);
- if (is_file($fileName)) {
- $ext = strrchr($fileName, '.');
- if ($ext == '.sql') {
- $this->content = file_get_contents($fileName);
- } elseif ($ext == '.gz') {
- $this->content = implode('', gzfile($fileName));
- } else {
- $this->error('無法識別的文件格式!');
- }
- } else {
- $this->error('文件不存在!');
- }
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 把數據寫入磁盤
- * +------------------------------------------------------------------------
- */
- private function setFile() {
- $recognize = '';
- $recognize = $this->dbName;
- $fileName = $this->trimPath($this->config['path'] . $this->dir_sep . $recognize . '_' . date('YmdHis') . '_' . mt_rand(100000000, 999999999) . '.sql');
- $path = $this->setPath($fileName);
- if ($path !== true) {
- $this->error("無法創建備份目錄目錄 '$path'");
- }
- if ($this->config['isCompress'] == 0) {
- if (!file_put_contents($fileName, $this->content, LOCK_EX)) {
- $this->error('寫入文件失敗,請檢查磁盤空間或者權限!');
- }
- } else {
- if (function_exists('gzwrite')) {
- $fileName .= '.gz';
- if ($gz = gzopen($fileName, 'wb')) {
- gzwrite($gz, $this->content);
- gzclose($gz);
- } else {
- $this->error('寫入文件失敗,請檢查磁盤空間或者權限!');
- }
- } else {
- $this->error('沒有開啟gzip擴展!');
- }
- }
- if ($this->config['isDownload']) {
- $this->downloadFile($fileName);
- }
- }
- private function trimPath($path) {
- return str_replace(array('/', '//', '//', '////'), $this->dir_sep, $path);
- }
- private function setPath($fileName) {
- $dirs = explode($this->dir_sep, dirname($fileName));
- $tmp = '';
- foreach ($dirs as $dir) {
- $tmp .= $dir . $this->dir_sep;
- if (!file_exists($tmp) && !@mkdir($tmp, 0777))
- return $tmp;
- }
- return true;
- }
- //未測試
- private function downloadFile($fileName) {
- ob_end_clean();
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header('Content-Description: File Transfer');
- header('Content-Type: application/octet-stream');
- header('Content-Length: ' . filesize($fileName));
- header('Content-Disposition: attachment; filename=' . basename($fileName));
- readfile($fileName);
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 給字符串添加 ` `
- * +------------------------------------------------------------------------
- * * @ $str 字符串
- * +------------------------------------------------------------------------
- * * @ 返回 `$str`
- * +------------------------------------------------------------------------
- */
- private function backquote($str) {
- return "`{$str}`";
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 獲取數據庫的所有表
- * +------------------------------------------------------------------------
- * * @ $dbName 數據庫名稱
- * +------------------------------------------------------------------------
- */
- private function getTables($dbName = '') {
- if (!emptyempty($dbName)) {
- $sql = 'SHOW TABLES FROM ' . $dbName;
- } else {
- $sql = 'SHOW TABLES ';
- }
- $result = $this->model->query($sql);
- $info = array();
- foreach ($result as $key => $val) {
- $info[$key] = current($val);
- }
- return $info;
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 把傳過來的數據 按指定長度分割成數組
- * +------------------------------------------------------------------------
- * * @ $array 要分割的數據
- * * @ $byte 要分割的長度
- * +------------------------------------------------------------------------
- * * @ 把數組按指定長度分割,并返回分割后的數組
- * +------------------------------------------------------------------------
- */
- private function chunkArrayByByte($array, $byte = 5120) {
- $i = 0;
- $sum = 0;
- $return = array();
- foreach ($array as $v) {
- $sum += strlen($v);
- if ($sum < $byte) {
- $return[$i][] = $v;
- } elseif ($sum == $byte) {
- $return[++$i][] = $v;
- $sum = 0;
- } else {
- $return[++$i][] = $v;
- $i++;
- $sum = 0;
- }
- }
- return $return;
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 備份數據 { 備份每張表、視圖及數據 }
- * +------------------------------------------------------------------------
- * * @ $tables 需要備份的表數組
- * +------------------------------------------------------------------------
- */
- private function backup($tables) {
- if (emptyempty($tables))
- $this->error('沒有需要備份的數據表!');
- $this->content = '/* This file is created by MySQLReback ' . date('Y-m-d H:i:s') . ' */';
- foreach ($tables as $i => $table) {
- $table = $this->backquote($table); //為表名增加 ``
- $tableRs = $this->model->query("SHOW CREATE TABLE {$table}"); //獲取當前表的創建語句
- if (!emptyempty($tableRs[0]["Create View"])) {
- $this->content .= "/r/n /* 創建視圖結構 {$table} */";
- $this->content .= "/r/n DROP VIEW IF EXISTS {$table};/* MySQLReback Separation */ " . $tableRs[0]["Create View"] . ";/* MySQLReback Separation */";
- }
- if (!emptyempty($tableRs[0]["Create Table"])) {
- $this->content .= "/r/n /* 創建表結構 {$table} */";
- $this->content .= "/r/n DROP TABLE IF EXISTS {$table};/* MySQLReback Separation */ " . $tableRs[0]["Create Table"] . ";/* MySQLReback Separation */";
- $tableDateRow = $this->model->query("SELECT * FROM {$table}");
- $valuesArr = array();
- $values = '';
- if (false != $tableDateRow) {
- foreach ($tableDateRow as &$y) {
- foreach ($y as &$v) {
- if ($v=='') //糾正empty 為0的時候 返回tree
- $v = 'null'; //為空設為null
- else
- $v = "'" . mysql_escape_string($v) . "'"; //非空 加轉意符
- }
- $valuesArr[] = '(' . implode(',', $y) . ')';
- }
- }
- $temp = $this->chunkArrayByByte($valuesArr);
- if (is_array($temp)) {
- foreach ($temp as $v) {
- $values = implode(',', $v) . ';/* MySQLReback Separation */';
- if ($values != ';/* MySQLReback Separation */') {
- $this->content .= "/r/n /* 插入數據 {$table} */";
- $this->content .= "/r/n INSERT INTO {$table} VALUES {$values}";
- }
- }
- }
- // dump($this->content);
- // exit;
- }
- }
- if (!emptyempty($this->content)) {
- $this->setFile();
- }
- return true;
- }
- /* -
- * +------------------------------------------------------------------------
- * * @ 還原數據
- * +------------------------------------------------------------------------
- * * @ $fileName 文件名
- * +------------------------------------------------------------------------
- */
- private function recover_file($fileName) {
- $this->getFile($fileName);
- if (!emptyempty($this->content)) {
- $content = explode(';/* MySQLReback Separation */', $this->content);
- foreach ($content as $i => $sql) {
- $sql = trim($sql);
- if (!emptyempty($sql)) {
- $mes = $this->model->execute($sql);
- if (false === $mes) { //如果 null 寫入失敗,換成 ''
- $table_change = array('null' => '/'/'');
- $sql = strtr($sql, $table_change);
- $mes = $this->model->execute($sql);
- }
- if (false === $mes) { //如果遇到錯誤、記錄錯誤
- $log_text = '以下代碼還原遇到問題:';
- $log_text.="/r/n $sql";
- set_log($log_text);
- } //Vevb.com
- }
- }
- } else {
- $this->error('無法讀取備份文件!');
- }
- return true;
- }
- }
- ?>
新聞熱點
疑難解答