MySQLデータベースを.sql
ファイルにエクスポートするためのPHPコードとは何ですか?
シェルにアクセスできないため、exec
を使用できません。 コードを見つけました ですが、コードに目を通しましたが、このコードは古く、うまく書かれていません。私が見つけたほとんどの指示はシェルアクセスを必要とします…残りは時代遅れです。
前もって感謝します。
PHPスクリプトを使用してデータベースをエクスポートする最良の方法。
または、特定のテーブルの5番目のパラメーター(配列)を追加します。複数のテーブルの場合はarray("mytable1","mytable2","mytable3")
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "Your Username";
$mysqlPassword = "Your Password";
$mysqlHostName = "Your Host";
$DbName = "Your Database Name here";
$backup_name = "mybackup.sql";
$tables = "Your tables";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($Host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($Host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__Rand".Rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
このツールは便利な場合があります。純粋なPHPベースのエクスポートユーティリティです。 https://github.com/2createStudio/shuttle-export
以下を試してください。
PHPファイルからデータベースバックアップクエリを実行します。以下は、テーブルバックアップを作成するためにSELECT INTO OUTFILEクエリを使用する例です。
<?php
$DB_Host = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_Host, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>
バックアップを復元するには、次のようにLOAD DATA INFILEクエリを実行するだけです。
<?php
$DB_Host = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_Host, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
* nixシステムでは、WHICHコマンドを使用してmysqldumpの場所を表示します。これを試してください:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'test';
$mysqldump=exec('which mysqldump');
$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql";
exec($command);
?>
これが私のコードです。MySQLデータベースをバックアップし、指定されたパスに保存します。
<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";
$mysqli = new mysqli($options['db_Host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SHOW TABLES");
while($row = $results->fetch_array()){
if (!in_array($row[0], $options['db_exclude_tables'])){
$mtables[] = $row[0];
}
}
foreach($mtables as $table){
$contents .= "-- Table `".$table."` --\n";
$results = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $results->fetch_array()){
$contents .= $row[1].";\n\n";
}
$results = $mysqli->query("SELECT * FROM ".$table);
$row_count = $results->num_rows;
$fields = $results->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$r = 0;
while($row = $results->fetch_array()){
if(($r % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($r+1) == $row_count || ($r % 400) == 399){
$contents .= ");\n\n";
}else{
$contents .= "),\n";
}
$r++;
}
}
}
if (!is_dir ( $options['db_backup_path'] )) {
mkdir ( $options['db_backup_path'], 0777, true );
}
$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";
$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "Backup file created '--$backup_file_name' ($result)";
}
fclose($fp);
return $backup_file_name;
}
$options = array(
'db_Host'=> 'localhost', //mysql Host
'db_uname' => 'root', //user
'db_password' => '', //pass
'db_to_backup' => 'attendance', //database name
'db_backup_path' => '/htdocs', //where to backup
'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);
次のことを行うことをお勧めします。
<?php
function EXPORT_TABLES($Host, $user, $pass, $name, $tables = false, $backup_name = false)
{
$mysqli = new mysqli($Host, $user, $pass, $name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while ($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if ($tables !== false)
{
$target_tables = array_intersect($target_tables, $tables);
}
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
foreach ($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM ' . $table);
$fields_amount = $result->field_count;
$rows_num = $mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE ' . $table);
$TableMLine = $res->fetch_row();
$content .= "\n\n" . $TableMLine[1] . ";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
{
while ($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter % 100 == 0 || $st_counter == 0)
{
$content .= "\nINSERT INTO " . $table . " VALUES";
}
$content .= "\n(";
for ($j = 0; $j < $fields_amount; $j++)
{
$row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
if (isset($row[$j]))
{
$content .= '"' . $row[$j] . '"';
}
else
{
$content .= '""';
} if ($j < ($fields_amount - 1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
} $st_counter = $st_counter + 1;
}
} $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__Rand" . Rand(1, 11111111) . ".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
echo $content;
exit;
}
?>
エクスポートおよびインポートのenitreプロジェクトは https://github.com/tazotodua/useful-php-scripts にあります。
次のことを行うことをお勧めします
<?php
$con = mysqli_connect('HostName', 'UserName', 'Password', 'DatabaseName');
$tables = array();
$result = mysqli_query($con,"SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($con, "SELECT * FROM ".$table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i=0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.'VALUES(';
for ($j=0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';} else { $return .= '""';}
if($j<$num_fields-1){ $return .= ','; }
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$handle = fopen('backup.sql', 'w+');
fwrite($handle, $return);
fclose($handle);
echo "success";
?>