원격 서버에서 내 홈 서버로 MySQL 테이블의 데이터를 쉽게 내 보낸 다음 가져올 수있는 방법이 필요합니다. 서버에 직접 액세스 할 수 없으며 phpMyAdmin과 같은 유틸리티가 설치되어 있지 않습니다. 그러나 서버에 PHP 스크립트를 넣을 수있는 기능이 있습니다.
데이터는 어떻게 얻습니까?
이 방법을 기록하기 위해 순수하게이 질문을합니다
이를 위해 SQL을 사용할 수 있습니다.
$file = 'backups/mytable.sql';
$result = mysql_query("SELECT * INTO OUTFILE '$file' FROM `##table##`");
그런 다음 디렉토리/파일 (backups/mytable.sql)에서 브라우저 또는 FTP 클라이언트를 지정하십시오. 예를 들어 파일 이름이 타임 스탬프 인 경우 증분 백업을 수행하는 좋은 방법이기도합니다.
해당 파일에서 데이터베이스로 다시 가져 오려면 다음을 사용할 수 있습니다.
$file = 'backups/mytable.sql';
$result = mysql_query("LOAD DATA INFILE '$file' INTO TABLE `##table##`");
다른 옵션은 PHP를 사용하여 서버에서 시스템 명령을 호출하고 'mysqldump'를 실행하는 것입니다.
$file = 'backups/mytable.sql';
system("mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip > ".$file);
CSV로 내 보낸 다음 사용 가능한 유틸리티로 가져옵니다. php : // output 스트림을 사용하는 것이 좋습니다.
$result = $db_con->query('SELECT * FROM `some_table`');
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
또한 하나의 파일 인 phpMinAdmin 도 고려해야하므로 업로드 및 설정이 쉽습니다.
작동 솔루션 (최신 버전 : Export.php + Import.php )
EXPORT_TABLES("localhost","user","pass","db_name");
암호:
//https://github.com/tazotodua/useful-php-scripts
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); }
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";
header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\""); echo $content; exit;
}
http://www.webyog.com 이것은 훌륭한 GUI 관리 도구이며 정말 깔끔한 HTTP- 턴링 기능을 가지고 있습니다 (이것이 기업에서 몇 달러를 지불해야합니다).
기본적으로 스크립트가 제공하는 스크립트를 웹 공간 (php 스크립트)에 업로드하고 sqlyog 관리자를 지정하면 데이터베이스에 액세스 할 수 있습니다. 이 스크립트를 사용하여 홈 클라이언트와 서버 간의 요청/쿼리를 터널링/프록시합니다.
나는이 방법을 사용하는 사람이 적어도 1 명 이상이라는 것을 알고 있습니다.
FTP/SFTP 액세스 권한이 있으면 계속해서 phpMyAdmin을 직접 업로드하십시오.
이 작은 패키지를 사용하여 FTP 액세스 권한이있는 서버에서 자동 mysql 백업을 수행합니다.
http://www.taw24.de/download/pafiledb.php?PHPSESSID=b48001ea004aacd86f5643a72feb2829&action=viewfile&fid=43&id=1
이 사이트는 독일어이지만 다운로드에는 영어 문서도 있습니다.
빠른 구글도 이것을 나타내지 만, 나는 그것을 직접 사용하지 않았습니다.
http://snipplr.com/view/173/mysql-dump/
다음은 데이터베이스의 모든 테이블을 백업하는 PHP
스크립트입니다. 이 기능은 http://davidwalsh.name/backup-mysql-database-php 을 기반으로합니다. 우선 foreign key restrictions
가 올바르게 설정됩니다.
내 설정에서 스크립트는 월요일의 특정 요일에 실행됩니다. 월요일에 실행되지 않은 경우 화요일 (예 :)에 실행되어 .sql
파일을 실행하여 이전 월요일의 날짜로 실행합니다. 4 주 전에 .sql
파일이 지워 지므로 항상 마지막 4 개의 백업이 유지됩니다. 코드는 다음과 같습니다.
<?php
backup_tables();
// backup all tables in db
function backup_tables()
{
$day_of_backup = 'Monday'; //possible values: `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` `Sunday`
$backup_path = 'databases/'; //make sure it ends with "/"
$db_Host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'movies_database_1';
//set the correct date for filename
if (date('l') == $day_of_backup) {
$date = date("Y-m-d");
} else {
//set $date to the date when last backup had to occur
$datetime1 = date_create($day_of_backup);
$date = date("Y-m-d", strtotime($day_of_backup.' -7 days'));
}
if (!file_exists($backup_path.$date.'-backup'.'.sql')) {
//connect to db
$link = mysqli_connect($db_Host,$db_user,$db_pass);
mysqli_set_charset($link,'utf8');
mysqli_select_db($link,$db_name);
//get all of the tables
$tables = array();
$result = mysqli_query($link, 'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
//disable foreign keys (to avoid errors)
$return = 'SET FOREIGN_KEY_CHECKS=0;' . "\r\n";
$return.= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\r\n";
$return.= 'SET AUTOCOMMIT=0;' . "\r\n";
$return.= 'START TRANSACTION;' . "\r\n";
//cycle through
foreach($tables as $table)
{
$result = mysqli_query($link, 'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$num_rows = mysqli_num_rows($result);
$i_row = 0;
//$return.= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
if ($num_rows !== 0) {
$row3 = mysqli_fetch_fields($result);
$return.= 'INSERT INTO '.$table.'( ';
foreach ($row3 as $th)
{
$return.= '`'.$th->name.'`, ';
}
$return = substr($return, 0, -2);
$return.= ' ) VALUES';
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysqli_fetch_row($result))
{
$return.="\n(";
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#\n#","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
if (++$i_row == $num_rows) {
$return.= ");"; // last row
} else {
$return.= "),"; // not last row
}
}
}
}
$return.="\n\n\n";
}
// enable foreign keys
$return .= 'SET FOREIGN_KEY_CHECKS=1;' . "\r\n";
$return.= 'COMMIT;';
//set file path
if (!is_dir($backup_path)) {
mkdir($backup_path, 0755, true);
}
//delete old file
$old_date = date("Y-m-d", strtotime('-4 weeks', strtotime($date)));
$old_file = $backup_path.$old_date.'-backup'.'.sql';
if (file_exists($old_file)) unlink($old_file);
//save file
$handle = fopen($backup_path.$date.'-backup'.'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
}
?>
SELECT * INTO OUTFILE
에 대한 권한이 충분하지 않은 것으로 나타났습니다. 그러나 다른 접근 방식에 비해 중첩 된 루프를 실제로 줄일 수있는 충분한 PHP (iteting and imploding)를 사용할 수있었습니다.
$dbfile = tempnam(sys_get_temp_dir(),'sql');
// array_chunk, but for an iterable
function iter_chunk($iterable,$chunksize) {
foreach ( $iterable as $item ) {
$ret[] = $item;
if ( count($ret) >= $chunksize ) {
yield $ret;
$ret = array();
}
}
if ( count($ret) > 0 ) {
yield $ret;
}
}
function tupleFromArray($assocArr) {
return '('.implode(',',array_map(function($val) {
return '"'.addslashes($val).'"';
},array_values($assocArr))).')';
}
file_put_contents($dbfile,"\n-- Table $table --\n/*\n");
$description = $db->query("DESCRIBE `$table`");
$row = $description->fetch_assoc();
file_put_contents($dbfile,implode("\t",array_keys($row))."\n",FILE_APPEND);
foreach ( $description as $row ) {
file_put_contents($dbfile,implode("\t",array_values($row))."\n",FILE_APPEND);
}
file_put_contents($dbfile,"*/\n",FILE_APPEND);
file_put_contents($dbfile,"DROP TABLE IF EXISTS `$table`;\n",FILE_APPEND);
file_put_contents($dbfile,array_pop($db->query("SHOW CREATE TABLE `$table`")->fetch_row()),FILE_APPEND);
$ret = $db->query("SELECT * FROM `$table`");
$chunkedData = iter_chunk($ret,1023);
foreach ( $chunkedData as $chunk ) {
file_put_contents($dbfile, "\n\nINSERT INTO `$table` VALUES " . implode(',',array_map('tupleFromArray',$chunk)) . ";\n", FILE_APPEND );
}
readfile($dbfile);
unlink($dbfile);
외래 키가있는 테이블이있는 경우이 방법은 올바른 순서로 테이블을 삭제 한 다음 올바른 (역순) 순서로 다시 만들면 여전히 작동 할 수 있습니다. CREATE
문은 외래 키 종속성을 생성합니다. SELECT * FROM information_schema.referential_constraints
를 통해 해당 순서를 결정하십시오.
외래 키에 순환 종속성이있는 경우 삭제하거나 만들 수있는 순서가 없습니다. 이 경우 끝에 모든 외래 키를 생성하는 phpMyAdmin의 지시를 따를 수 있습니다. 그러나 이것은 또한 CREATE
문을 조정해야 함을 의미합니다.