We usually use phpmyadmin for importing a large sql file to our database. There are tons of other options are there to do this. Most of the people use the phpMyAdmin tool for their database maintenance operations. But most of the host you have to login to cpanel and then navigate to the phpMyAdmin from there.
In this tutorial we are demonstrating how to make our own application that import a .sql file using PHP script. This little php script helps you to restore our MySQL database with very few steps.
How to import sql file in MySQL database using PHP?
The following details needed in hand to perform the import action using PHP.
- $filename – Required. The filename of dumped database.
- $mysqlHost– Required. The mysql Host name
- $mysqlUser – Required. The mysql server username.
- $mysqlPassword – Required. The MySql user password. Often this can be empty for your localhost mysql installaiton. But it’s a must when you go in the production server.
- $mysqlDatabase – The selected database that you need to import data.
<?php // Name of the data file $filename = 'mydump.sql'; // MySQL host $mysqlHost = 'localhost'; // MySQL username $mysqlUser = 'root'; // MySQL password $mysqlPassword = ''; // Database name $mysqlDatabase = 'newdatabase'; // Connect to MySQL server $link = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPassword, $mysqlDatabase) or die('Error connecting to MySQL Database: ' . mysqli_error()); $tempLine = ''; // Read in the full file $lines = file($filename); // 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 its semicolon at the end, so that is the end of one query if (substr(trim($line), -1, 1) == ';') { // Perform the query mysqli_query($link, $tempLine) or print("Error in " . $tempLine .":". mysqli_error()); // Reset temp variable to empty $tempLine = ''; } } echo "Tables imported successfully"; ?>
You may be find this post useful, Create Simple Login Script in PHP and MySql
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
the line
mysqli_query($tempLine) or print(“Error in ” . $tempLine .”:”. mysqli_error());
must be
mysqli_query($link, $tempLine) or print(“Error in ” . $tempLine .”:”. mysqli_error());
then it works well
Yes You are Right. Thanks for pointing this. Updated the script.