简体   繁体   中英

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?

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.

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');
}

. 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.

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

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