首页 > 解决方案 > 使用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 不正确时,我没有得到任何错误回报当我运行上面的代码时,我会在终端上看到错误,但它不会将错误保存在变量中。

标签: phpmysql

解决方案


<?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";
?>

也许以这种方式导入会起作用,不确定这是您需要的,但应该可以。来自如何使用 php 在 mysql 数据库中导入 .sql 文件的代码


您可以使用该--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 个参数,因此可能尝试同时获取这两个参数,其中一个可能包含错误消息。

希望这可以帮助


推荐阅读