Current Location: Home> Latest Articles> How to elegantly print mysqli::$errno with error message in PHP

How to elegantly print mysqli::$errno with error message in PHP

M66 2025-05-17

When using mysqli for database operations in PHP, you often encounter situations where error messages need to be printed. Usually, the mysqli extension provides error code ( mysqli::$errno ) and error information ( mysqli::$error ) to help us promptly feedback problems when an error occurs. But how do you print these error messages gracefully to make the error log clearer and easier to debug? This article will show you how to use mysqli::$errno gracefully to print error codes and error messages in PHP.

1. Basic mysqli error handling

First, let’s take a look at how to use mysqli for database connection and basic error handling in PHP. In mysqli connection object, error messages and error codes can be obtained through the mysqli::$error and mysqli::$errno properties.

Sample code:

 <?php
$host = 'localhost';
$username = 'root';
$password = 'password';
$database = 'test_db';

// create MySQLi connect
$conn = new mysqli($host, $username, $password, $database);

// 检查connect是否成功
if ($conn->connect_error) {
    echo "connect失败: " . $conn->connect_error;
    exit();
}

// Execute a query
$sql = "SELECT * FROM non_existing_table";
$result = $conn->query($sql);

// Check whether the query is successful
if (!$result) {
    // Print error codes and error messages
    echo "Error code: " . $conn->errno . "<br>";
    echo "error message: " . $conn->error;
}

// 关闭connect
$conn->close();
?>

explain:

  • Use connect_error to check whether the database connection is successful.

  • Use errno and error to get error codes and error information.

  • When executing a query, if an error occurs, the details are output via errno and error .

2. Handle and record error messages gracefully

Although it is effective to output error messages directly, in production environments, we usually want to log error logs and avoid exposing sensitive information to the end user. In actual development, elegant error handling can not only help developers quickly locate problems, but also improve system security and user experience.

Example: Logging error message

We can use the error_log() function to write error information to the log file. Here is the improved code:

 <?php
$host = 'localhost';
$username = 'root';
$password = 'password';
$database = 'test_db';

$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    // use error_log 记录connect错误
    error_log("connect失败: " . $conn->connect_error, 3, "/var/log/php_errors.log");
    exit();
}

$sql = "SELECT * FROM non_existing_table";
$result = $conn->query($sql);

if (!$result) {
    // Log error log
    error_log("Error code: " . $conn->errno . " error message: " . $conn->error, 3, "/var/log/php_errors.log");

    // 输出友好的error message
    echo "Operation failed,Please try again later。";
}

$conn->close();
?>

explain:

  • Use error_log() to write error information to the specified log file (such as /var/log/php_errors.log ).

  • Display user-friendly error messages on the front end to avoid exposing too much technical details.

  • Write errors to the file through the 3- parameter setting.

3. Elegantly disable error output in production environment

In production environments, we usually disable PHP error display and log it in the log. To prevent sensitive error information from being exposed to end users, we can disable error output by modifying php.ini or using the following code:

Sample code:

 <?php
// Disable error display
ini_set('display_errors', '0');

// Enable error logging
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php_errors.log');

// connect数据库并Execute a query
$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    // 记录connect错误
    error_log("connect失败: " . $conn->connect_error, 3, "/var/log/php_errors.log");
    exit();
}

$sql = "SELECT * FROM non_existing_table";
$result = $conn->query($sql);

if (!$result) {
    // 记录error message
    error_log("Error code: " . $conn->errno . " error message: " . $conn->error, 3, "/var/log/php_errors.log");
    echo "Operation failed,Please try again later。";
}

$conn->close();
?>

explain:

  • ini_set('display_errors', '0') : Disable error display.

  • ini_set('log_errors', '1') : Enable error logging.

  • Error message is recorded to the specified file through the error_log() function.

4. Use custom error handling functions

To make error handling more flexible, we can define a custom error handling function in which mysqli::$errno and mysqli::$error are handled uniformly. This reduces duplicate code and improves maintainability of the code.

Sample code:

 <?php
// Custom error handling functions
function handleMysqliError($conn) {
    // Log errors to log
    error_log("Error code: " . $conn->errno . " error message: " . $conn->error, 3, "/var/log/php_errors.log");

    // 显示友好的error message
    echo "Operation failed,Please try again later。";
}

// create数据库connect
$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    handleMysqliError($conn);
    exit();
}

$sql = "SELECT * FROM non_existing_table";
$result = $conn->query($sql);

if (!$result) {
    handleMysqliError($conn);
}

$conn->close();
?>

explain:

  • The handleMysqliError function encapsulates the logic of error handling.

  • When an error occurs, calling the function directly not only simplifies the code, but also ensures a unified error handling method.

Conclusion

In PHP, it is very common to print error messages using mysqli::$errno and mysqli::$error . In order to make error handling more elegant and secure, we can improve the robustness and user experience of the system through logging, disabling error output, using custom error handling functions, etc.

Hope this article helps you better understand how to handle errors in database operations gracefully in PHP. If you have any questions, please leave a message to discuss!