1、本地環境
web:apache
php:PHP 7.0.10 (cli) (built: Aug 18 2016 09:48:53) ( ZTS )
mysql: 5.7.14
2、基本思路
- 獲取備份數據表名
- 獲取備份表結構
- 獲取數據
- 寫入數據到文件
3、獲取表名
- 獲取所有數據表名,可以在頁面上做一個選擇數據表的功能,選擇部分數據表。
//使用pdo連接數據庫
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'root', '');
//查詢所有的數據表名
$tables = $pdo->query('SHOW TABLE STATUS')->fetchAll(\PDO::FETCH_ASSOC);
//數據結果如下:
array (
0 =>
array (
'Name' => 'article',
'Engine' => 'MyISAM',
'Version' => '10',
'Row_format' => 'Dynamic',
'Rows' => '0',
'Avg_row_length' => '0',
'Data_length' => '0',
'Max_data_length' => '281474976710655',
'Index_length' => '1024',
'Data_free' => '0',
'Auto_increment' => '1',
'Create_time' => '2018-11-28 15:52:30',
'Update_time' => '2018-11-28 15:52:30',
'Check_time' => NULL,
'Collation' => 'utf8mb4_general_ci',
'Checksum' => NULL,
'Create_options' => '',
'Comment' => '',
),
1 =>
array (
'Name' => 'user',
...
),
)
4、獲取表的表結構
- 這里以user表為例
//使用pdo連接數據庫
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'root', '');
//查詢表結構
$struct = $pdo->query('SHOW CREATE TABLE user')->fetchAll(\PDO::FETCH_ASSOC);
//結果如下:
array (
0 =>
array (
'Table' => 'user',
'Create Table' => 'CREATE TABLE `user` (
`userId` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4',
),
)
//獲取表結構字符串並寫入到文件中
$str = $struct[0]['Create Tabl'];
//寫入到文件中
file_put_contents();//
5、獲取表中數據
//使用pdo連接數據庫
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'root', '');
//查詢數據,以user表為主,如果數據量大的話采用分頁查詢
$data = $pdo->query('SELECT * FROM `user`')->fetchAll(\PDO::FETCH_ASSOC);
//組裝insert語句
foreach($data as $row) {
$row = array_map('addslashes', $row);
$sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
$sql = "INSERT INTO `{$table}` VALUES ({$str});\n";
//寫入到文件
file_put_contents();
}
- 說明:上面轉義字段時,如果字段中null值在轉義時會轉成空字符串,需要注意一下,如果要求null不能轉義成空字符串,可以自己拼接字符串,例如:
$str = '';
if ($row === null) {
$str = 'null,';
} else {
$str .= $row . ',';
}
$str = rtrim($str);
6、總結
- 這種備份試適合對小數據量的數據進行備份,如有大量的數據備份還需要進行一定的優化
- 后續完善后會繼續修改本文章