0

我使用http://davidwalsh.name/backup-mysql-database-php来备份我的 mysql 数据库。但它会破坏数据库中的二进制数据(blob)。这意味着,导入生成的文件会创建不可读的 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);
}
4

1 回答 1

0

我只会看这篇文章的评论。

当您从 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);

可以单独处理另一个进程的各种输入/输出流的更复杂的设置涉及 using proc_open(),但这是非常高级的东西,在您的情况下可能没有必要。

于 2012-11-27T23:51:36.510 回答