Restore MySQL Database from SQL File using PHP

Restore MySQL Database from SQL File using PHP

Restore MySQL Database from SQL File using PHP

Generally we use PHPmyadmin to restore our database . Suppose in some cases if you don’t have access to your live server’s cpanel , PHPmyadmin .
Now, you will learn to know that how to restore MySQL database from SQL File using PHP .

This is also useful for any user that if you want to allow to create a database backup from your website .
We will guide below in simple PHP script to restore mysql Database .

We have created a function ‘database_restore’ for better handling this task .

    • $db_host

– This is required and it specifies the hostname.

    • $user

– This is required and it specifies the database’s username.

    • $pass

– This is required and it specifies the database’s password.

    • $db_name

– This is required and it specifies the database name that you wants to take backup.

    • $file_path

– This is required and it specifies the sql file’s path

function database_restore($db_host, $user, $pass, $db_name, $file_path){
    // Connect & select the database
    $db = new mysqli($db_host, $user, $pass, $db_name); 

    // Temporary variable, used to store current query
    $templine = '';
    
    // Read in entire file
    $lines = file($file_path);
    
    $error = '';
    
    // Loop through each line
    foreach ($lines as $line){
        // Skip it if it's a comment
        if(substr($line, 0, 2) == '--' || $line == ''){
            continue;
        }
        
        // Add this line to the current segment
        $templine .= $line;
        
        // If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';'){
            // Perform the query
            if(!$db->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $db-&gt;error . '

‘; } // Reset temp variable to empty $templine = ”; } } return !empty($error)?$error:true; }

To use above function ‘database_restore’:

$db_host     = 'localhost';
$user = 'root';
$pass = '';
$db_name     = 'db_name';
$file_path   = 'path/to/your/mysql_backup_file.sql';

database_restore($db_host, $user, $pass, $db_name, $file_path);

If you have any query , you can write on below comment . I will try my best to reply soon .
we also provide PHP advance level training .