简体   繁体   中英

Backing up a MySQL database using PHP

I was trying to make a backup of my MySQL db called "backup" using a PHP script below, but for some reason, it doesnt work. Any ideas what is wrong? I wanted to create a file called test.sql in the same folder that would contain the data (because the db is quite big I only selected values of Temp>35, but I could change that later). Right now when I run it, I get the echo, but no file created.

<?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";
?>

Just Try.

$query  = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName WHERE Temp>35";
$result = mysql_query($query) or die(mysql_error());
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";
  ?>
<?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");
    }

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM