【问题标题】:Get MySQL Error Message from Only the Error Code仅从错误代码中获取 MySQL 错误消息
【发布时间】:2016-03-13 17:57:41
【问题描述】:

MySQL 错误代码(如 1054)有什么意义?

错误消息包含实际信息,因此必须有某种方法可以从错误代码中获取更多信息。

但是与错误消息相比,我可以使用什么来仅从错误代码中获取任何信息?

通常你会得到两个:

<?PHP
$db_link = new mysqli($hostname, $username, $password, $database);

$statement = $db_link->prepare('SELECT SomeFieldThatDoesNotExist FROM Person');
$statement->execute();

if(!$statement) {
    $specific_error = $db_link->error;
    $error_number = $db_link->errno;
}
?>

假设我有错误 1054(请参阅:https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_field_error)。

只有数字 1054,我可以使用什么来获取实际的 MySQL 错误消息本身?

【问题讨论】:

  • 有一些方法...您可以运行perror ${errno} 并捕获其输出(默认情况下应与 MySQL 服务器一起安装,iirc),或者您可以读取/解析 MySQL 源文件...这取决于你真正想要完成什么。
  • @Michael-sqlbot:不是这样。 $errno 是一个常量,而不是变量。
  • 我使用${errno} 不是 php 意义上的,而是作为一个泛型变量,表示任意 MySQL 错误号。从 1 到 3999 循环遍历 $n 的所有值,运行 perror ${n} 并捕获其输出。
  • 回想起来,OP 的方法存在问题,因为许多错误都有占位符值。例如,Incorrect key file for table '%s'; try to repair it(错误 1034)在以后可能不是那么有用,因为表名是未知的。只保存错误号是有损的。
  • @Michael-sqlbot:你说得对,我的问题措辞非常糟糕(大约两年前)。我正在纠正这个建议,并以我应该思考的方式进行重定向。

标签: php mysql debugging mysqli errno


【解决方案1】:

使用 Github 上的 MySQL 错误代码 PHP 库:https://github.com/HoldOffHunger/mysql-errors-codes

正常的错误消息样式:

$db_link = new mysqli($this->hostname,$this->username,$this->password);
print($db_link->connect_errno . " : " . $db_link->connect_error);

正常的错误消息输出:

13236 : Message: Newly created data directory SOMEDIRECTORY is unusable. You can safely remove it.

新的、更完整的错误消息样式:

$mysql_error = new MySQLErrorCode();
$error_codes = $mysql_error->ErrorCodes();

print_r($error_codes[13236]);

输出:

13236 : Message: Newly created data directory SOMEDIRECTORY is unusable. You can safely remove it.

'13236' => [
    'error_code' => '13236',
    'internal_code' => 'ER_DATA_DIRECTORY_UNUSABLE',
    'message_template' => 'Message: Newly created data directory %s is unusable. You can safely remove it.',
    'sql_state' => 'HY000',
    'version_information' => 'ER_DATA_DIRECTORY_UNUSABLE was added in 8.0.13.'
],

【讨论】:

    【解决方案2】:

    使用显示错误;

    手册:https://mariadb.com/kb/en/mariadb/show-errors/

    SELECT f();
    ERROR 1305 (42000): FUNCTION f does not exist
    
    SHOW COUNT(*) ERRORS;
    +-----------------------+
    | @@session.error_count |
    +-----------------------+
    |                     1 |
    +-----------------------+
    
    SHOW ERRORS;
    +-------+------+---------------------------+
    | Level | Code | Message                   |
    +-------+------+---------------------------+
    | Error | 1305 | FUNCTION f does not exist |
    +-------+------+---------------------------+
    

    【讨论】:

    • 我的问题更多:如果您只有“1305”(例如,来自多年前的日志文件),您可以在 mysql 中使用什么内部方法来获取其余的错误信息? (级别、消息、sqlstate等。)
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多