php - 在php中使用系统函数返回变量中的mysql错误

标签 php mysql

我正在尝试使用 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不正确时,我没有收到任何错误返回 当我运行上面的代码时,我在终端上看到错误,但它不会将错误保存在变量中。

最佳答案

<?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 个参数,因此也许尝试同时获取这两个参数,其中一个可能会包含错误消息。

希望这有帮助

关于php - 在php中使用系统函数返回变量中的mysql错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50348428/

相关文章:

php - mysql只获取一个字段

php - 为多个表编写 INSERT 查询

mysql - 错误: bundle install failed for mysql gem

php - mysql md5(md5 ('pass' ) + salt) 不等于 php md5(md5 ('pass' ).salt)

php5_invoke xdebug : no action - module was disabled by maintainer for apache2 SAPI

php - .htaccess 打开 .css 而不是 .php

php - USAePay源码中ereg_replace转preg_replace

php - 如何在对象中的数组中询问某些对象

mysql - MySQL 表连接中的 "using"和 "on"有什么区别?

mysql - 为什么我的查询没有返回任何结果?