Current Location: Home> Latest Articles> Create an encapsulation function to centrally process the mysqli_stmt::$error error message

Create an encapsulation function to centrally process the mysqli_stmt::$error error message

gitbox 2025-05-28

Using MySQL databases is a very common operation when developing PHP applications. Usually, developers use the mysqli extension to interact with the database when executing SQL queries, and the mysqli_stmt class is the main interface for preparing and executing SQL statements. Although mysqli provides rich error handling mechanisms, developers may ignore or repeat database errors when using them. In order to improve development efficiency and maintainability of the code, encapsulating a function to centrally handle the mysqli_stmt::$error error message is an effective solution.

This article will introduce how to encapsulate a function and manage mysqli_stmt::$error error information in a unified manner, thereby improving the error management efficiency of database operations.

1. Use mysqli_stmt::$error to get error information

In PHP, when executing SQL statements using mysqli_stmt , the error information of the database operation can be obtained through the mysqli_stmt::$error attribute. When a database query or operation fails, the mysqli_stmt::$error property returns an error string. If there is no error, the return value is an empty string.

Here is a simple example that demonstrates how to get error information using mysqli_stmt::$error :

 <?php
$mysqli = new mysqli("localhost", "username", "password", "database");

$stmt = $mysqli->prepare("SELECT * FROM non_existent_table");
$stmt->execute();

if ($stmt->error) {
    echo "Error: " . $stmt->error;
}

$stmt->close();
$mysqli->close();
?>

In the above example, when executing a query, $stmt->error returns an error message if the database table does not exist.

2. Create an encapsulation function to handle errors in a centralized manner

In order to improve the efficiency of error management in database operations, we can create an encapsulation function. This function can receive the mysqli_stmt object as a parameter, check whether there are any errors, and record or display error messages. In this way, when an error occurs, we do not need to manually check mysqli_stmt::$error every time, but handle it through a unified function.

The following is the implementation of the encapsulation function:

 <?php
function handleQueryError($stmt) {
    if ($stmt->error) {
        // Here you can log error information to the log file
        // Or directly output error information
        error_log("SQL Error: " . $stmt->error); // Log error log
        die("Database operation failed,Please try again later!"); // End the script and display user-friendly error message
    }
}

$mysqli = new mysqli("localhost", "username", "password", "database");

$stmt = $mysqli->prepare("SELECT * FROM non_existent_table");
$stmt->execute();

// Use encapsulated functions to handle errors
handleQueryError($stmt);

$stmt->close();
$mysqli->close();
?>

In this example, the handleQueryError() function checks for errors and logs the error message to the log file. If an error occurs, it outputs a user-friendly error message and stops the script execution.

3. Encapsulation function extension: Support different error handling strategies

Depending on different application scenarios, different error handling strategies may be required. For example, in some cases, developers may wish to log error messages to a database or email them to administrators. In order to enhance the flexibility of the encapsulation function, we can extend the handleQueryError() function to support different error handling methods.

Here is an extended encapsulation function that supports logging errors to databases, log files, or sending emails to administrators:

 <?php
function handleQueryError($stmt, $logToDatabase = false, $sendEmail = false) {
    if ($stmt->error) {
        // Log errors to log file
        error_log("SQL Error: " . $stmt->error);

        // If you need to record it to the database
        if ($logToDatabase) {
            $mysqli = new mysqli("localhost", "username", "password", "database");
            $errorMessage = $stmt->error;
            $stmt = $mysqli->prepare("INSERT INTO error_logs (message) VALUES (?)");
            $stmt->bind_param("s", $errorMessage);
            $stmt->execute();
            $stmt->close();
            $mysqli->close();
        }

        // If you need to send an email to the administrator
        if ($sendEmail) {
            mail("[email protected]", "Database Error", "SQL Error: " . $stmt->error);
        }

        die("Database operation failed,Please try again later!");
    }
}

$mysqli = new mysqli("localhost", "username", "password", "database");

$stmt = $mysqli->prepare("SELECT * FROM non_existent_table");
$stmt->execute();

// Use extended version functions,And log errors to log and send emails
handleQueryError($stmt, true, true);

$stmt->close();
$mysqli->close();
?>

In this version of the encapsulation function, the developer can choose whether to log error information to the database or notify the administrator via email.

4. Summary

By encapsulating a function to centrally process mysqli_stmt::$error error information, it can greatly improve the error management efficiency of database operations. This method allows developers to not need to repeatedly write error handling codes in each database operation, and also facilitates later maintenance and expansion. You can flexibly adjust error handling strategies according to the needs of the project, such as recording to files, databases, or sending email notifications. This can help developers discover and deal with potential problems in database operations in a timely manner, and improve application stability and user experience.