php數(shù)據(jù)庫備份還原類分享
來源:易賢網(wǎng) 閱讀:1110 次 日期:2014-08-22 10:01:37
溫馨提示:易賢網(wǎng)小編為您整理了“php數(shù)據(jù)庫備份還原類分享”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了php數(shù)據(jù)庫備份還原類,需要的朋友可以參考下

代碼如下:

<?php

/**

* 數(shù)據(jù)庫備份還原類

* @author xialeistudio<admin@xialeistudio.net>

* Class DatabaseTool

*/

class DatabaseTool

{

private $handler;

private $config = array(

'host' => 'localhost',

'port' => 3306,

'user' => 'root',

'password' => '',

'database' => 'test',

'charset' => 'utf-8',

'target' => 'sql.sql'

);

private $tables = array();

private $error;

private $begin; //開始時(shí)間

/**

* 架構(gòu)方法

* @param array $config

*/

public function __construct($config = array())

{

$this->begin = microtime(true);

$config = is_array($config) ? $config : array();

$this->config = array_merge($this->config, $config);

//啟動(dòng)PDO連接

if (!$this->handler instanceof PDO)

{

try

{

$this->handler = new PDO("mysql:host={$this->config['host']}:{$this->config['port']};dbname={$this->config['database']}", $this->config['user'], $this->config['password']);

}

catch (PDOException $e)

{

$this->error = $e->getMessage();

return false;

}

catch (Exception $e)

{

$this->error = $e->getMessage();

return false;

}

}

}

/**

* 備份

* @param array $tables

* @return bool

*/

public function backup($tables = array())

{

//存儲(chǔ)表定義語句的數(shù)組

$ddl = array();

//存儲(chǔ)數(shù)據(jù)的數(shù)組

$data = array();

$this->setTables($tables);

if (!empty($this->tables))

{

foreach ($this->tables as $table)

{

$ddl[] = $this->getDDL($table);

$data[] = $this->getData($table);

}

//開始寫入

$this->writeToFile($this->tables, $ddl, $data);

}

else

{

$this->error = '數(shù)據(jù)庫中沒有表!';

return false;

}

}

/**

* 設(shè)置要備份的表

* @param array $tables

*/

private function setTables($tables = array())

{

if (!empty($tables) && is_array($tables))

{

//備份指定表

$this->tables = $tables;

}

else

{

//備份全部表

$this->tables = $this->getTables();

}

}

/**

* 查詢

* @param string $sql

* @return mixed

*/

private function query($sql = '')

{

$stmt = $this->handler->query($sql);

$stmt->setFetchMode(PDO::FETCH_NUM);

$list = $stmt->fetchAll();

return $list;

}

/**

* 獲取全部表

* @return array

*/

private function getTables()

{

$sql = 'SHOW TABLES';

$list = $this->query($sql);

$tables = array();

foreach ($list as $value)

{

$tables[] = $value[0];

}

return $tables;

}

/**

* 獲取表定義語句

* @param string $table

* @return mixed

*/

private function getDDL($table = '')

{

$sql = "SHOW CREATE TABLE `{$table}`";

$ddl = $this->query($sql)[0][1] . ';';

return $ddl;

}

/**

* 獲取表數(shù)據(jù)

* @param string $table

* @return mixed

*/

private function getData($table = '')

{

$sql = "SHOW COLUMNS FROM `{$table}`";

$list = $this->query($sql);

//字段

$columns = '';

//需要返回的SQL

$query = '';

foreach ($list as $value)

{

$columns .= "`{$value[0]}`,";

}

$columns = substr($columns, 0, -1);

$data = $this->query("SELECT * FROM `{$table}`");

foreach ($data as $value)

{

$dataSql = '';

foreach ($value as $v)

{

$dataSql .= "'{$v}',";

}

$dataSql = substr($dataSql, 0, -1);

$query .= "INSERT INTO `{$table}` ({$columns}) VALUES ({$dataSql});rn";

}

return $query;

}

/**

* 寫入文件

* @param array $tables

* @param array $ddl

* @param array $data

*/

private function writeToFile($tables = array(), $ddl = array(), $data = array())

{

$str = "/*rnMySQL Database Backup Toolsrn";

$str .= "Server:{$this->config['host']}:{$this->config['port']}rn";

$str .= "Database:{$this->config['database']}rn";

$str .= "Data:" . date('Y-m-d H:i:s', time()) . "rn*/rn";

$str .= "SET FOREIGN_KEY_CHECKS=0;rn";

$i = 0;

foreach ($tables as $table)

{

$str .= "-- ----------------------------rn";

$str .= "-- Table structure for {$table}rn";

$str .= "-- ----------------------------rn";

$str .= "DROP TABLE IF EXISTS `{$table}`;rn";

$str .= $ddl[$i] . "rn";

$str .= "-- ----------------------------rn";

$str .= "-- Records of {$table}rn";

$str .= "-- ----------------------------rn";

$str .= $data[$i] . "rn";

$i++;

}

echo file_put_contents($this->config['target'], $str) ? '備份成功!花費(fèi)時(shí)間' . (microtime(true) - $this->begin) . 'ms' : '備份失敗!';

}

/**

* 錯(cuò)誤信息

* @return mixed

*/

public function getError()

{

return $this->error;

}

public function restore($path = '')

{

if (!file_exists($path))

{

$this->error('SQL文件不存在!');

return false;

}

else

{

$sql = $this->parseSQL($path);

try

{

$this->handler->exec($sql);

echo '還原成功!花費(fèi)時(shí)間', (microtime(true) - $this->begin) . 'ms';

}

catch (PDOException $e)

{

$this->error = $e->getMessage();

return false;

}

}

}

/**

* 解析SQL文件為SQL語句數(shù)組

* @param string $path

* @return array|mixed|string

*/

private function parseSQL($path = '')

{

$sql = file_get_contents($path);

$sql = explode("rn", $sql);

//先消除--注釋

$sql = array_filter($sql, function ($data)

{

if (empty($data) || preg_match('/^--.*/', $data))

{

return false;

}

else

{

return true;

}

});

$sql = implode('', $sql);

//刪除/**/注釋

$sql = preg_replace('//*.**//', '', $sql);

return $sql;

}

}

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:php數(shù)據(jù)庫備份還原類分享
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)