-
Notifications
You must be signed in to change notification settings - Fork 300
Importing dump from php
diego torres edited this page Sep 2, 2024
·
11 revisions
Snipped from stackoverflow, not tested, but looks nice. Comment if useful!
https://stackoverflow.com/questions/19751354/how-to-import-sql-file-in-mysql-database-using-php
http://stackoverflow.com/a/13246630/1050264
error_reporting(E_ALL);
$filename = 'dump.sql';
$mysql_host = 'localhost';
$mysql_username = 'root';
$mysql_password = '';
$mysql_database = 'dump';
// Connect to MySQL server
$link = mysqli_connect($mysql_host, $mysql_username, $mysql_password, $mysql_database); or die('Error connecting to MySQL server: ' . mysqli_connect_error());
// Temporary variable, used to store current query
$templine = '';
$handle = fopen($filename , 'r');
if ($handle) {
while (!feof($handle)) { // Loop through each line
$line = trim(fgets($handle));
// 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
mysqli_query($link, $templine) or print('Error performing query "' . $templine . '":' . mysqli_error($link) . PHP_EOL);
// Reset temp variable to empty
$templine = '';
}
}
fclose($file);
}
echo "Tables imported successfully";
If for example you would like/need to trim any comments (mysqldump-php/mysql uses comments to keep compatibility between mysql versions) you could use this regex as suggested by @KevsRepos in #263.
$sql = trim(preg_replace("/\/\*(?:.|\n)*?\*\/\s*;/", '', $file));