How to Restore Mysql Database Using PHP


Hello guys.. Today I am going to share a PHP script that requested by many of My friends and YouTube viewers after creating the tutorial about How to backup MySQL Database using PHP.

In this tutorial you will learn to Re-store MYSQL Database using PHP Script. So, lets get in to the tutorial. 

How to Restore Mysql Database Using PHP:

First of all create a page and name it "restore.php" in your public directory and copy the code that I shared below to it.
$conn = mysqli_connect("localhost", "root", "", "YOUR DATABASE NAME");
$filePath = "Your Database File Here to Backup";
function restoreMysqlDB($filePath, $conn)
    $sql = '';
    $error = '';
    if (file_exists($filePath)) {
        $lines = file($filePath);
        foreach ($lines as $line) {
            // Ignoring comments from the SQL script
            if (substr($line, 0, 2) == '--' || $line == '') {
            $sql .= $line;
            if (substr(trim($line), - 1, 1) == ';') {
                $result = mysqli_query($conn, $sql);
                if (! $result) {
                    $error .= mysqli_error($conn) . "\n";
                $sql = '';
        } // end foreach
        if ($error) {
            $response = array(
                "type" => "error",
                "message" => $error
        } else {
            $response = array(
                "type" => "success",
                "message" => "Database Restore Completed Successfully."
    } // end if file exists
    return $response;
  • On the above code change the "YOUR DATABASE NAME" with your Database Name.
  • Change "Your Database File Here to Backup" with the file .SQL File location that you want to Re-Store.
Example: I took a backup of a database name "Accessories" and saved to "c://backup/accessories.sql". Now I am going to edit the script like the following.

Will change the "YOUR DATABASE NAME" with "Accessories" and "Your Database File Here to Backup" with "c://backup/accessories.sql". 

Now run the script.. It will take time as per your Database Size.

Topics You May Like to Read:

I hope you like this article. Please let me know your comments and feedback by using the comment box that given below. Thank you.
This is the most recent post.
Older Post