How to Import SQL File in MySQL Database with PHP
This simple PHP code is used to Import SQL file in MySQL database. same place and run the PHP file through a site address.
The file contents into an array of lines by using the PHP file(). The line array is iterated in a foreach loop to construct the query by omitting comments and empty lines.
We have to read the sql file and than execute it.
Here, Two way to import sql file with php. you can use any method.
Way 1 : file_get_contents Function
<?php
$filename = 'sql_file.sql';
$host = 'localhost'; //Hostname
$username = 'root'; //Username
$password = '******'; //Password
$database = 'database_name'; //Database Name
$link = mysqli_connect($host,$username,$password,$database);
if(! $link ) {
die('Could not connect: ' . mysqli_error($link));
}
echo 'MySQL Connected successfully<br />';
$sqlSources = file_get_contents($filename);
$retval = mysqli_multi_query($link, $sqlSources);
if(! $retval ) {
echo 'Not created table: ' . mysqli_error($conn);
}
echo "Tables imported successfully!";
?>
Way 2 : mysqli_query Function
<?php
$filename = 'sql_file.sql';
$host = 'localhost'; //Hostname
$username = 'root'; //Username
$password = '******'; //Password
$database = 'database_name'; //Database Name
$link = mysqli_connect($host,$username,$password,$database);
if(! $link ) {
die('Could not connect: ' . mysqli_error($link));
}
echo 'MySQL Connected successfully<br />';
$templine = '';
$filesLoad = file($filename);
foreach ($filesLoad as $load) {
if (substr($load, 0, 2) == '--' || $load == '')
continue;
$templine .= $load;
if (substr(trim($load), -1, 1) == ';') {
$link->query($templine) or print('Query Error . $templine . : ' . mysqli_error($link) . '<br /><br />');
$templine = '';
}
}
echo "Tables imported successfully!";
mysqli_close($link);