Deval Khandelwal
Deval Khandelwal

Reputation: 3548

How to restore a mysql database in php

I am trying to restore a mysql database using php. I googled and found out this piece of code :-

<?php

$restore_file  = "backup.bkp";
$server_name   = "localhost";
$username      = "root";
$password      = "pass";
$database_name = "db";

$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name}  
<  $restore_file";
exec($cmd);

?>

I am using a shared server (linux) and the file was restored using phpmyadmin successfully. But I want to use php to restore. The code does not work. Where am I being wrong?

Upvotes: 1

Views: 1161

Answers (3)

Deval Khandelwal
Deval Khandelwal

Reputation: 3548

Thanks to @Scoopy, I found that exec() was disabled my by hosting provider. However, I have solved my problem using the following code I found here :-

$db = mysql_connect ( 'localhost', 'username', 'pass' ) or die('not connected');
mysql_select_db( 'test', $db) or die('Not found');
$fp = fopen ( 'backup-file', 'r' );
$fetchData = fread ( $fp, filesize ( 'backup-file') );
$sqlInfo = explode ( ";\n", $fetchData); // explode dump sql as a array data    

foreach ($sqlInfo AS $sqlData )
{
mysql_query ( $sqlData ) or die('Query not executed');
}

BUT, THE CODE IS DEPRECATED. So, I made up this code :-

$host = 'localhost'; 
$user = 'root';
$password = 'root';
$database = 'test';

$conn = new mysqli($host, $user, $password, $database);
$conn->autocommit(FALSE);

$fp = fopen('bkp-file', 'r');
$fetchData = fread($fp, filesize('bkp-file'));
$sqlInfo = explode(";\n", $fetchData); // explode dump sql as a array data

foreach ($sqlInfo AS $sqlData) {
    $conn->query($sqlData);
}
$conn->commit();
$conn->close();

This code is perfect to use. It uses transactions to prevent multiple writes.

Upvotes: 2

Scopey
Scopey

Reputation: 6319

Generally a shared hosting server will disable access to system functions as it introduces a security risk for them. You can confirm this if your server provider allows you to use the phpinfo command (docs).

Create a page that dumps the PHP info and then look on that page for a setting called disable_functions - it's under the "Core" section. If exec appears there then you will know that exec is a disabled function and you will not be able to use it. Unfortunately one of the drawbacks of using some shared hosting services as it is impossible/very difficult to implement the sorts of things you are talking about.

Upvotes: 1

meda
meda

Reputation: 45500

I don't see why you need PHP, you can do this directly in the terminal.

Backup

mysqldump -u root -p db> backup.bkp

Restore

mysql -u root -p db < backup.bkp

Upvotes: 0

Related Questions