簡體   English   中英

使用PHP的MySQL數據庫的二進制安全備份

[英]Binary-safe backup of MySQL database using PHP

我使用http://davidwalsh.name/backup-mysql-database-php備份了我的mysql數據庫。 但是它會破壞數據庫中的二進制數據(斑點)。 這意味着,導入生成的文件會創建不可讀的Blob。

應該改變什么?

為了您的方便,以下是代碼:

backup_tables('localhost','username','password','blog');


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{

  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);

  //get all of the tables
  if($tables == '*')
  {
    $tables = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result))
    {
      $tables[] = $row[0];
    }
  }
  else
  {
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  //cycle through
  foreach($tables as $table)
  {
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);

    $return.= 'DROP TABLE '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";

    for ($i = 0; $i < $num_fields; $i++) 
    {
      while($row = mysql_fetch_row($result))
      {
        $return.= 'INSERT INTO '.$table.' VALUES(';
        for($j=0; $j<$num_fields; $j++) 
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = ereg_replace("\n","\\n",$row[$j]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  }

  //save file
  $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
  fwrite($handle,$return);
  fclose($handle);
}

我將只關注這篇文章的評論。

當您從PHP中運行其他進程時,應檢查返回碼,例如:

// execute process and capture output and return code in $out and $res
exec('/path/to/command', $out, $res);
if ($res) {
    // the process didn't return with code 0
}

在您的情況下, $out將為空,因為stderr用於打印錯誤消息。 要顯示捕獲的輸出中的內容,您可以像這樣重定向stderr

exec('/path/to/command 2>&1', $out, $res);

可以單獨處理另一個進程的各種輸入/輸出流的更復雜的設置涉及使用proc_open() ,但這是相當高級的東西,在您的情況下可能沒有必要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM