我正在尝试使用php中的system()导入数据库。 当我的sql文件正确时,它工作正常。 假设我在sql文件中有错误(例如,语法错误)。 我想要一个变量中的确切错误,这样我就可以保持日志和警报的目的。
<?php
$lastline = system("mysql -u root mydbname < /home/mydbname.sql ",$retval);
echo "\nretval:";
print_r($retval);
echo "\nlastline:";
print_r($lastline);
?>
不幸的是,当我的sql不正确时,我没有得到任何错误 当我运行上面的代码时,我会看到终端上的错误,但它不会将错误保存在变量中。
答案 0 :(得分:1)
<?php
$filename = '/home/mydbname.sql';
$mysql_host = 'localhost';
$mysql_username = 'root';
$mysql_password = '';
$mysql_database = 'mydbname';
// Connect to MySQL server & Select database
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
$lines = file($filename);
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 = '';
}
}
echo "Tables imported successfully";
?>
也许以这种方式导入会起作用,不确定这是你需要的,但它应该有效。 代码来自How to import .sql file in mysql database using php
您可以使用--force (-f)
标志,以便MySQL不会停止并只记录任何错误到控制台:
mysql -u userName -p -f -D dbName < script.sql
<?php
$lastline = system("mysql -u root -f mydbname < /home/mydbname.sql ",$retval);
echo "\nretval:";
print_r($retval);
echo "\nlastline:";
print_r($lastline);
?>
exec()上的PHP文档为输出和返回值指定了另外2个参数,因此可能尝试获取两个参数,其中一个可能包含错误消息。
希望这有帮助