MySQLのバックアップ

ファイル名:mysql_export.php

サンプルコード:

 

<?php
class MysqlExport{

/**
* database connect
*/
private $_db;

private $_resource;

/**
* create table structure sql
*/
private $_create_table = ";

public function __construct($host = ", $user = ", $pass = ", $db = ", $port = 3306) {
if (empty($host) || empty($user)) {

} else {
$this->real_connect($host, $user, $pass, $db, $port);
}
}

public function init() {
return $this;
}

/**
* データベースに接続
*/
public function real_connect($host, $user, $pass, $db = ", $port = 3306) {
$this->_db = mysql_connect($host . ':’ . $port, $user, $pass);
if ($db) {
$this->select_db($db);
}
return $this->init();
}

/**
* データベースを選択
*/
public function select_db($db) {
if (mysql_select_db($db, $this->_db)) {
return true;
}
}

/**
* クエリー
*/
public function query($sql) {
if ($this->_db) {
if ($this->_resource = mysql_query($sql, $this->_db)) {
return $this->init();
}
}
throw new Exception($this->get_error());
}

/**
* 結果セットを取得
*/
public function fetch_array($arg = MYSQL_BOTH) {
$result = array();
if ($this->_resource && !mysql_errno($this->_db)) {
while ($rs = mysql_fetch_array($this->_resource, $arg)) {
$result[] = $rs;
}
}
return $result;
}

/**
* エラーが表示され
*/
public function get_error() {
return mysql_errno($this->_db) . “: " . mysql_error($this->_db). “\n";
}

/**
* データテーブルを表示
*/
public function show_tables($table = ") {
$sql = “SHOW TABLES";
$sql .= $table ? " LIKE '{$table}'" : ";
$result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
return $result;
}

/**
* データテーブルのフィールド表示
*/
public function show_columns($table) {
if (empty($table)) {
return array();
}
$sql = “SHOW FULL COLUMNS FROM {$table}";
$result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
return $result;
}

/**
* データテーブルの状態表示
*/
public function show_table_status($table) {
if (empty($table)) {
return array();
}
$result = $this->query(“SHOW TABLE STATUS LIKE '{$table}'")->fetch_array(MYSQL_ASSOC);
$result = reset($result);
return $result;
}

/**
* データのテーブル構造表示
*/
public function show_create_table($table) {
if (empty($table)) {
return ";
}
$this->_create_table = “CREATE TABLE IF NOT EXISTS `{$table}`(" . PHP_EOL;
$table_status = $this->show_table_status($table);
$columns = $this->show_columns($table);

foreach ($columns AS $col) {
$this->_create_table .= “`{$col['Field’]}` {$col['Type’]} NOT NULL {$col['Extra’]}," . PHP_EOL;
}

$this->_create_table .= $this->create_indexSyntax($table);

$char = substr($table_status['Collation’], 0, strpos($table_status['Collation’], '_’));
$table_status['Auto_increment’] = $table_status['Auto_increment’] ? $table_status['Auto_increment’] : 0;
$this->_create_table .= “)Engine={$table_status['Engine’]} AUTO_INCREMENT={$table_status['Auto_increment’]} DEFAULT CHARSET={$char};" . str_repeat(PHP_EOL, 3);

return $this->_create_table;
}

/**
* トリガ表示
*/
public function show_constraint($db_name) {
if (empty($db_name)) {
return array();
}
$sql = “SELECT a.CONSTRAINT_NAME AS constrint_name, a.TABLE_name AS table_name, a.COLUMN_NAME AS column_name, a.REFERENCED_TABLE_NAME as referenced_table_name, a.REFERENCED_COLUMN_NAME AS referenced_column_name, b.UPDATE_RULE as update_rule, b.DELETE_RULE AS delete_rule FROM information_schema.KEY_COLUMN_USAGE AS a LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS AS b ON a.constraint_name=b.constraint_name WHERE a.constraint_schema = '{$db_name}’ AND a.POSITION_IN_UNIQUE_CONSTRAINT = 1";
$result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
}

/**
*インデックス表示
*/
public function show_index($table) {
if (empty($table)) {
return array();
}
$sql = “SHOW INDEX FROM {$table}";
$result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
return $result;
}

/**
* データベース構造表示
*/
public function show_database_char() {
$sql = “SHOW VARIABLES LIKE 'character_set_database'";
$char = $this->query($sql)->fetch_array(MYSQL_ASSOC);
return reset($char);
}

/**
* インデックス構文を作成
*/
public function create_indexSyntax($table) {
if (empty($table)) {
return array();
}
$indexing = $this->show_index($table);
$syntax = array();
$indexSyntax = array();
foreach ($indexing as $index) {
$syntax[$index['Index_type’]][$index['Key_name’]][] = $index['Column_name’];
}

foreach ($syntax as $index_type => $index_value) {
foreach ($index_value as $key_name => $columns) {
if ($key_name == 'PRIMARY’) {
$indexSyntax[] = 'PRIMARY KEY (`’ . implode(“`,`", $columns) . '`)’;
} else {
if ($index_type == 'FULLTEXT’) {
$indexSyntax[] = “FULLTEXT KEY `{$key_name}` (`" . implode(“`,`", $columns) . '`)’;
} else{
$indexSyntax[] = “KEY `{$key_name}` USING {$index_type} (`" . implode(“`,`", $columns) . '`)’;
}
}
}
}

return implode(',’ . PHP_EOL, $indexSyntax) . PHP_EOL;
}

/**
* insert構文
*/
public function create_insertSyntax($table) {
if (empty($table)) {
return ";
}
$sql = “SELECT * FROM {$table}";
$result = $this->query($sql)->fetch_array(MYSQL_ASSOC);
$insertStr = ";
if ($result) {
$first = reset($result);
$key = implode('`,`’, array_keys($first));
$insert = “INSERT INTO `{$table}` (`{$key}`) VALUES “;
$valuesStr = array();
foreach ($result as $value) {
$values = array();
foreach ($value as $v) {
$v = mysql_real_escape_string($v);
$values[] = preg_replace(“#\\\+#", “\\", $v);
}
$valuesStr[] = “('" . implode(“','", $values) . “')";
}
$valuesStr = array_chunk($valuesStr, 5000);
foreach ($valuesStr as $str) {
$insertStr .= $insert . implode(',’, $str) . ';’ . PHP_EOL;
}

}
return $insertStr . str_repeat(PHP_EOL, 3);
}

}

$export = ";
$test = new MysqlExport('localhost’, 'root’, ", 'pm_cms’);
$char = $test->show_database_char();
$test->query(“SET NAMES {$char['Value’]}");
$tables = $test->show_tables();
foreach ($tables as $table) {
list($table_name) = array_values($table);
$export .= $test->show_create_table($table_name);
$export .= $test->create_insertSyntax($table_name);
}
$fp = fopen('pm_cms.sql’, 'w’);
fwrite($fp, $export);
fclose($fp);
?>

Source

Posted by arkgame