Current Location: Home> Latest Articles> How to implement a fault tolerance mechanism for failed operations through mysqli_stmt::$error

How to implement a fault tolerance mechanism for failed operations through mysqli_stmt::$error

gitbox 2025-05-28

In actual development, when executing database queries, we often need to judge whether the query is successful. If the query fails, it will not only affect the normal operation of the system, but may also lead to program exceptions or data inconsistencies. Therefore, it is very important to adopt effective fault tolerance mechanisms to capture and deal with these failures. The mysqli_stmt::$error function can help developers obtain detailed information about SQL query failures, and thus take corresponding measures to restore the normal operation of the system.

1. What is mysqli_stmt::$error ?

mysqli_stmt::$error is a property of the mysqli_stmt class in MySQLi. After executing the SQL statement, it returns the error message of the MySQL query. If there is no error in the query, it will return an empty string. Through this property, we can get the specific cause of the error when the query fails.

2. Use mysqli_stmt::$error to perform fault-tolerant processing after query failure

Here is a basic example showing how to use mysqli_stmt::$error to handle MySQL query failures.

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

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

// Check if the connection is successful
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// Prepare SQL Query
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);

// 检查Prepare语句是否成功
if (!$stmt) {
    die('SQL 语句Prepare失败: ' . $conn->error);
}

// 绑定参数并执行Query
$id = 1;
$stmt->bind_param("i", $id);

if (!$stmt->execute()) {
    // Query失败,Output error message
    echo 'Query失败: ' . $stmt->error;
} else {
    // Query成功,Processing results
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        echo "user ID: " . $row['id'] . "<br>";
    }
}

// Close the connection
$stmt->close();
$conn->close();
?>

3. Explain the fault tolerance mechanism in the code

  • Connect to the database : First, use the mysqli class to create a database connection. If the connection fails, directly output the error message and exit.

  • Prepare SQL statement : We use $conn->prepare($sql) to prepare the query statement. If statement preparation fails, use $conn->error to get the error message.

  • Bind parameters and execute query : Before executing the query, we bind the query parameters and check whether it is successful during the execution. If execute() returns false , it means that the query failed, and then use $stmt->error to obtain the error information and output it.

  • Query successful : If the query is successful, the result is obtained through get_result() and displayed.

4. Further enhancement of error handling

In actual development, we often need more detailed error handling. In the above code, we simply output the error message, but in a production environment, the error message should not be directly exposed to the user, but should be logged and provide users with friendly prompts.

 <?php
// Error log function
function logError($message) {
    $logFile = 'error_log.txt';
    $date = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$date] $message\n", FILE_APPEND);
}

// 执行Query时,If it fails,Log error message to log
if (!$stmt->execute()) {
    logError('Query失败: ' . $stmt->error);
    echo 'Query失败,Please try again later。';
}
?>

In this example, when the query fails, the error message will be logged into a file named error_log.txt and will not be directly exposed to the user. This helps developers to track errors when problems arise without affecting the user experience.

5. Conclusion

By using mysqli_stmt::$error , we can easily capture error information when MySQL query fails and take corresponding measures based on these error information. Whether it is simply outputting error messages or recording errors into log files, it can effectively improve the stability and reliability of the system. A good fault tolerance mechanism can not only help developers quickly locate problems when errors occur, but also improve the user experience and ensure that the system does not crash when encountering problems.