How to import / restore MySql tables using PHP

MySql tables

If you sensitive to import MySql tables upon run times of php application as well as here I am going to operate you how you can easily modernize 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 conclusive for importing database during installation of php application following wordpress, joomla, drupal etc subsequently below is the easy PHP method for importing mysql database without PHPMyAdmin.

Importing MySql Tables Using PHP

Use along along along in the middle of php script to import / restore mysql database tables.

 

<?php
    // Set database credentials
   $hostname     = 'localhost'; // MySql Host
   $username = 'root'; // MySql Username
   $password = 'root'; // MySql Password
   $dbname     = 'dbname'; // MySql Database Name
   // File Path which need to import
   $filePath   = 'sql_files/mysql_db.sql';
 
    // Connect & select the database
   $con = new mysqli($hostname, $username, $password, $dbname);
 
    // Temporary variable, used to store current query
    $templine = '';
 
    // Read in entire file
    $lines = file($filePath);
 
    $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(!$con->query($templine)){
                $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $db->error . '<br /><br />';
            }
 
            // Reset temp variable to empty
            $templine = '';
        }
    }
    $con->close();
    echo  !empty($error)?$error:"Import Success";
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.