Current Location: Home> Latest Articles> How to write a more stable database access layer using mysqli_stmt::$error

How to write a more stable database access layer using mysqli_stmt::$error

gitbox 2025-05-28

In PHP development, database access is a common operation, especially when a project requires a large number of operations on the database, the stability and error handling of the database are particularly important. mysqli is a commonly used database extension in PHP. It provides some useful functions to help developers achieve efficient and reliable database access.

In this article, we will explore how to use the mysqli_stmt::$error function to improve the stability of the database access layer. mysqli_stmt::$error is a property in the mysqli_stmt class that is used to obtain error information that occurs when preprocessing statements are executed. By appropriately using this property, we can effectively catch and handle errors, ensuring that exceptions during database access can be properly managed, thereby improving system stability.

What is mysqli_stmt::$error ?

In PHP, the mysqli_stmt class is used to process prepared statements. By preprocessing statements, we can improve the performance of the query while avoiding SQL injection attacks. The mysqli_stmt::$error attribute is used to obtain error information that occurs when executing prepared statements. If the execution is successful, it returns an empty string. If execution fails, a string describing the error is returned.

Sample code:

 <?php
// Connect to the database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

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

// Prepare SQL Statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
if ($stmt === false) {
    die('PrepareStatement失败: ' . $mysqli->error);
}

// Bind parameters
$id = 1;
$stmt->bind_param("i", $id);

// 执行Statement
$stmt->execute();

// Check for errors
if ($stmt->error) {
    die('执行Statement失败: ' . $stmt->error);
} else {
    echo "Query successful!";
}

// 关闭Statement和连接
$stmt->close();
$mysqli->close();
?>

In the example above, we first establish a database connection and prepare an SQL query. Then, bind the parameters through bind_param and execute the statement. We check whether an error occurred during execution through the $stmt->error property. If there is an error, output the error message and stop execution.

How to improve stability using mysqli_stmt::$error ?

1. Catch SQL errors to avoid program crashes

mysqli_stmt::$error can help us catch errors in SQL execution and prevent the program from crashing when a database error occurs. By judging whether $stmt->error is empty, we can discover the problem in time and give corresponding prompts to prevent the error from continuing to propagate.

Sample code:

 <?php
$stmt = $mysqli->prepare("UPDATE users SET name = ? WHERE id = ?");
if ($stmt === false) {
    die("PrepareStatement失败: " . $mysqli->error);
}

// Simulate an error
$name = 'John Doe';
$id = 'invalid_id';  // Assume here ID invalid

$stmt->bind_param("si", $name, $id);
$stmt->execute();

// Check whether the execution is successful
if ($stmt->error) {
    die("Update failed: " . $stmt->error);
}
echo "Update successfully!";
?>

In this code, if an SQL error occurs or execution fails, the error message will be captured and output to ensure that the program does not crash due to the failure of the database operation.

2. Improve database connection stability

Using mysqli_stmt::$error can also improve the stability of database connections. For example, connection errors are common exceptions when accessing a database. Mysqli_stmt::$error can check the database connection status in time to avoid subsequent operations being unable to be executed due to connection failure.

Sample code:

 <?php
// Connect to the database时Check for errors
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Execute a database query
$query = "SELECT * FROM non_existent_table";
$result = $mysqli->query($query);

// Check whether the query execution is successful
if (!$result) {
    die("Query failed: " . $mysqli->error);
}

while ($row = $result->fetch_assoc()) {
    echo "username: " . $row['name'];
}

$mysqli->close();
?>

In this example, we deliberately execute a table where the query does not exist. By checking $mysqli->error and $stmt->error , we can capture and process errors in time, thus preventing the program from continuing to perform invalid operations.

3. Logging and error monitoring

In addition to displaying error messages on the front end, developers can also record error messages in the log to facilitate future troubleshooting and monitoring. Error information obtained through mysqli_stmt::$error can be written to a log file for analysis and resolution by developers.

Sample code:

 <?php
// Assume that the code that executes the query is the same as before
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

// Check for errors并Logging
if ($stmt->error) {
    // Logging
    error_log("Query failed: " . $stmt->error, 3, '/path/to/error.log');
    die("An error occurred,Please try again later。");
}
?>

In this way, error messages will be written to the log file, while users will see friendly prompts to avoid exposing sensitive database error details.

Summarize

mysqli_stmt::$error is a very practical property in PHP that helps developers catch and handle errors in SQL execution. By rationally utilizing this attribute, we can not only improve the stability of the database access layer, but also enhance the robustness of the application. In actual development, ensuring the stability of database operations is very important, and error capture and processing are key steps to ensure high system availability.