使用PHP备份MySQL数据库

时间:2013-12-22 16:50:26

标签: php mysql backup

我试图使用下面的PHP脚本备份我的MySQL数据库“备份”,但由于某种原因,它不起作用。有什么想法有什么不对?我想在包含数据的同一文件夹中创建一个名为test.sql的文件(因为db非常大,我只选择了Temp> 35的值,但我可以稍后更改)。现在,当我运行它时,我得到回声,但没有创建文件。

<?php
$dbhost = '...';
$dbuser = '...';
$dbpass = '...';
$dbname = 'backup';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$tableName  = 'backup';
$backupFile = 'test.sql';
$query      = "SELECT * WHERE Temp>35 INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);
echo "Backed up";
?>

3 个答案:

答案 0 :(得分:0)

试试吧。

$query  = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName WHERE Temp>35";
$result = mysql_query($query) or die(mysql_error());

答案 1 :(得分:0)

Try this and let me know:

  <?php
  $dbhost = '...';
  $dbuser = '...';
  $dbpass = '...';
  $dbname = 'backup';
  $conn = mysql_connect($dbhost, $dbuser, $dbpass);
  mysql_select_db($dbname);

  $databasename  = 'backup';
  $backupFile = 'test.sql';
  $query      = "SELECT * INTO OUTFILE '$backupFile' FROM $databasename WHERE Temp>35";
  $result = mysql_query($query);
  echo "Backed up";
  ?>

答案 2 :(得分:0)

<?php
    $source_db='source_db';
    $target_db='target_db';

    $server='127.0.0.1';
    $user='root';
    $password='';

    mysql_connect($server,$user,$password);
    mysql_select_db($source_db);

    // Get names of all tables in source database
    $result=mysql_query("show tables");
    while($row=mysql_fetch_array($result)){
        $name=$row[0];
        $this_result=mysql_query("show create table $name");
        $this_row=mysql_fetch_array($this_result);
        $tables[]=array('name'=>$name,'query'=>$this_row[1]);
    }

    // Connect target database to create and populate tables
    mysql_select_db($target_db);

    $total=count($tables);
    for($i=0;$i < $total;$i++){
        $name=$tables[$i]['name'];
        $q=$tables[$i]['query'];

        mysql_query($q);
        mysql_query("insert into $name select * from $source_db.$name");
    }

?>