Site Admin
Site Admin Founder of MeaningArticles
984 Views

Restore MySQL Database From SQL File Using PHP

Hello Dev.

Today i will explained How To Restore MySQL Database From SQL File Using PHP. This example is so easy to use in php.

This example to i am import to the sql file in file folder and store your all database table field to your new database in sql file through.

So let's start to the example.

index.php

<?php
    $dbHost     = 'localhost';
    $dbUsername = 'root';
    $dbPassword = 'root';
    $dbName     = 'db_backup';
    $filePath   = 'files/meaningarticles.sql';
    
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
    $templine = '';
    
    // Read in entire file
    $lines = file($filePath);
    $error = '';
    
    foreach ($lines as $line){
        // Skip it if it's a comment
        if(substr($line, 0, 2) == '--' || $line == ''){
            continue;
        }        
        
        $templine .= $line;
        
        if (substr(trim($line), -1, 1) == ';'){
            // Perform the query
            if(!$db->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $db->error . '<br /><br />';
            }            
            $templine = '';
        }
    }    
    return !empty($error)?$error:true;
?>

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.