使用php备份整个mysql数据库

时间:2016-03-26 15:07:45

标签: php mysql

我有这个代码我发现但是我有一个问题试图让它工作......它说没有文件和目录,这是什么意思,我该如何解决它?另外,我如何调整代码来备份整个数据库,而不仅仅是表:

<?php
    $servername = ""; //this is the local server name 
    $username   = ""; // this is mysql username for my database
    $password   = ""; // this is the database password
    $database   = ""; //this is the database name

    $conn = new mysqli($servername, $username, $password, $database); //this will create a connection to the database

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $table_name = "activities";
   $backup_file  = "/tmp/activities.sql";
   $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

   mysql_select_db('');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not take data backup: ' . mysql_error());
   }

   echo "Backedup  data successfully\n";

   mysql_close($conn);
?>

更新的代码:     

    $conn = new mysqli($servername, $username, $password, $database); //this will create a connection to the database

   if(! $conn ) {
      die('Could not connect: ' . mysqli_error());
   }

   $table_name = "activities";
   $backup_file  = "/tmp/activities.sql";
   $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

   mysqli_select_db('');
   $retval = mysqli_query( $sql, $conn );

   if(! $retval ) {
      die('Could not take data backup: ' . mysqli_error());
   }

   echo "Backedup  data successfully\n";

   mysqli_close($conn);
?>

1 个答案:

答案 0 :(得分:1)

您不需要mysqli_select_db('');已在第4个参数中声明数据库。

然后( $sql, $conn );连接首先( $conn, $sql );

然后mysqli_error()需要连接参数mysqli_error($conn)

这是一个重写,并分别为连接的4个变量填写4个参数。

<?php 

$servername = ""; //this is the local server name 
$username   = ""; // this is mysql username for my database
$password   = ""; // this is the database password
$database   = ""; //this is the database name

$conn = new mysqli($servername, $username, $password, $database); //this will create a connection to the database

   if(! $conn ) {
      die('Could not connect: ' . mysqli_error($conn));
   }

   $table_name = "activities";
   $backup_file  = "/tmp/activities.sql";
   $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

   $retval = mysqli_query( $conn, $sql );

   if(! $retval ) {
      die('Could not take data backup: ' . mysqli_error($conn));
   }

else {
   echo "Backed up data successfully\n";
}

   mysqli_close($conn);
?>

如果您还有其他问题,请查看mysqli_error($conn)抛出的内容,如果文件路径不正确,请使用错误报告,因此请确保PHP可以读取您的文件并且文件夹/文件是正确的权限设置。

error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code

旁注:只应在暂存时进行显示错误,而不是生产。