How to import / restore MySql tables using PHP

If you want to import mysql tables on run time of php application then here I am going to show you how you can easily restore mysql tables using PHP. Generally you use to import mysql database from PHPMyAdmin, It is one of the easiest method to import mysql database but if You are looking solution for importing database during installation of php application like wordpress, joomla, drupal etc then below is the simple PHP method for importing mysql database without PHPMyAdmin.



Importing MySql Tables Using PHP

Use following php script to import / restore mysql database tables.

<?php
    
   $hostname     = 'localhost'; 
   $username = 'root'; 
   $password = 'root'; 
   $dbname     = 'dbname'; 
   
   $filePath   = 'sql_files/mysql_db.sql';
 
    // Connect & select the database
   $con = new mysqli($hostname, $username, $password, $dbname);
 
    
    $templine = '';
 
    
    $lines = file($filePath);
 
    $error = '';
 
    
    foreach ($lines as $line){
        
        if(substr($line, 0, 2) == '--' || $line == ''){
            continue;
        }
 
        
        $templine .= $line;
 
        
        if (substr(trim($line), -1, 1) == ';'){
            
            if(!$con->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $db->error . '<br /><br />';
            }
 
            
            $templine = '';
        }
    }
    $con->close();
    echo  !empty($error)?$error:"Import Success";
?>