How to Import SQL into a Database using PHP

Importing square script thru programming may be beneficial while we need to create database shape dynamically. for example, if we provide APP or plugin to download and set up from online, the dynamic sq. import can be used to set up the utility database on the time of installing the APP or plugin.

On this academicwe’re going to import an sq. report right into a database the use of Hypertext Preprocessor programming. In this situationwe Have a record containing square for developing touch table and placing information. The PHP code parses the document line via line and extracts the question statements to execute using PHP MySQL function.

PHP Code to Import SQL

This simple PHP code is used to import SQL file into a database. It extracts the file contents into an array of lines by using PHP file(). The line array is iterated in a foreach loop to construct the query by omitting comment and empty lines.

$conn =new mysqli('localhost', 'root', '' , 'blog_samples');

$query = '';
$sqlScript = file('database-script.sql');
foreach ($sqlScript as $line)	{
	$startWith = substr(trim($line), 0 ,2);
	$endWith = substr(trim($line), -1 ,1);
	if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
	$query = $query . $line;
	if ($endWith == ';') {
		mysqli_query($conn,$query) or die('<div class="error-response sql-import-response">Problem in executing the SQL query <b>' . $query. '</b></div>');
		$query= '';		
echo '<div class="success-response sql-import-response">SQL file imported successfully</div>';


Please follow and like us:

Leave a Comment

Your email address will not be published. Required fields are marked *