I am trying to restore a database using the following code from http://www.a2zwebhelp.com/php-script-to-import-mysql-database But i am receiving "Error: Query was empty" Where am i going wrong?
Ps importing the sql file from phpmyadmin serves the purpose but doesnt work using this.
<?php
include 'connect.php';
$filename = 'DB_Backups/db-backup-08-04-14-08-39-16.sql';
$templine = '';
$lines = file($filename); //Read entire file
foreach($lines as $line){
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
$templine.=$line;
if(substr(trim($line), -1, 1) == ';'){
mysql_query($templine) or print('Error: '.mysql_error().'<br>');
$templine = '';
}
}
?>
Well, for one, this part of code doesn't skip comments, it literally adds them to your $templine
:
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
$templine.=$line;
Secondly, here you try to execute query with $templine
assigned above (if it ever was assigned, or otherwise ''
), where you actually want to execute query with $line
:
if(substr(trim($line), -1, 1) == ';'){
mysql_query($templine) or print('Error: '.mysql_error().'<br>');
So, basically this should work somewhat better:
foreach($lines as $line){
if(substr($line, 0, 2) == '--' || $line == '') //Skip all comments
continue;
if(substr(trim($line), -1, 1) == ';'){
mysql_query(trim($line)) or print('Error: '.mysql_error().'in ' . $line . '<br>');
}
}
A slight improvement and it works :) @ favoretti thank you for the hint.
<?php
// Name of the file
$filename = 'DB_Backups/'.$name;
// Temporary variable, used to store current query
$templine = '';
// Read in entire 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 it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.