PHP – Import .sql File in mySQL Database

Implemented php script which is imported mysql file into the database.

Copy and paste below php script into a file.

Save this file. (Example – import.php).

Replaced techguru_data.sql file name with your file name.

Run import.php on the browser and your tables are imported in your mysql database.

Demo – Import

import.php

<?php
// File Name
$filename = 'techguru_data.sql';
// Host Name
$mysql_host = 'localhost';
// Username
$mysql_username = 'root';
// Password
$mysql_password = '';
// Database Name
$mysql_database = 'techguru';

// Database Connect
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error! connecting to MySQL database: ' . mysql_error());
// Database Select
mysql_select_db($mysql_database) or die('Error! selecting MySQL database: ' . mysql_error());

// Temporary Variable
$templine = '';
// Read File
$get_lines = file($filename);
// Loop
foreach ($get_lines as $new_line){
// Skip
if (substr($new_line, 0, 2) == '--' || $new_line == '')
    continue;

// Add this line
$templine .= $new_line;
// End of the query
if (substr(trim($new_line), -1, 1) == ';'){
    // Run the query
    mysql_query($templine) or print('Error! performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
    // Reset temp variable
    $templine = '';
  }
}
 echo "Imported successfully";
?>

1 Comment on “PHP – Import .sql File in mySQL Database

  1. I’m no longer certain where you’re getting your info, however great
    topic. I needs to spend a while learning much more or working out more.

    Thanks for wonderful information I was searching for this info for
    my mission.

Leave a Reply

Your email address will not be published.

*