SAFEER N
SAFEER N

Reputation: 1197

PHP mysqldump file import

I want backup my local database and import that database from live website. I'm tried something. please see below..

My Backup code

<?php
$dbhost = "localhost"; 
$dbuser = "root";  
$dbpass = 'password'; 
$dbname = "database"; 

$backupfile ='database.sql';
$backupdir = dirname(__FILE__);
$source = $backupdir.'/'.$backupfile;
system("mysqldump -h $dbhost -u $dbuser --password='$dbpass' $dbname  > $backupfile");

?>
<form action="http://www.example.com/restore_database.php" method="post">
    <input type="text" name="backup_file" value="<?php echo $source; ?>"/>
    <input type="submit" />
</form>

my restore_database.php (example.com/restore_database.php)

<?php
$dbhost = "localhost";
$dbuser = "username";
$dbpass = 'password';
$dbname = "database";
$filename = $_POST['backup_file'];

mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to MySQL server: ' . mysql_error());
mysql_select_db($dbname) or die('Error selecting MySQL database: ' . mysql_error());

$templine = '';
$lines = file($filename);
foreach ($lines as $line) {
    if (substr($line, 0, 2) == '--' || $line == '')
        continue;
    $templine .= $line;
    if (substr(trim($line), -1, 1) == ';') {
        mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
        $templine = '';
    }
}
?>

In my localhost , I'm successfully tested this. for my live site I think file path not detect correctly. I have no idea about this. please help me. Thanks.

Upvotes: 1

Views: 4508

Answers (1)

a14m
a14m

Reputation: 8055

assuming that the live site lay on the ip 134.122.12.109 and you are using UNIX

on your local host create these files and ~/backupdir directory

backup.sh

#!/bin/bash
mysqldump -uusername -pPassword database > ~/backupdir/backupFile.sql

restore.sh

#!/bin.bash
mysql -h 134.122.12.109 -uliveSiteUsername -pLiveSitePassword database < ~/backupdir/backupFile.sql

now you can backup your localhost by running ./backup.sh

and you can restore the live site by using ./restore.sh

hope that demonstrated the idea.


responding to your comment

let the restore_database.php be

<?php
$dbhost = "localhost";
$dbuser = "username";
$dbpass = 'password';
$dbname = "database";
$filename = $_POST['backup_file'];
system("mysql -h $dbhost -u $dbuser --password='$dbpass' $dbname < $filename");
?>

Upvotes: 2

Related Questions