When developing web applications, error logging when handling database operations is crucial, especially in large projects, error tracking and resolution can greatly improve system stability and user experience. The mysqli extension in PHP provides a very useful feature, mysqli_stmt::$error , which can help us easily catch errors in database operations and log records.
This article will introduce how to use the mysqli_stmt::$error function to build an automatic error logging system and monitor database operation errors in real time. Through this method, you can ensure that when an error occurs, the system can respond quickly and record detailed error information, which facilitates subsequent troubleshooting and repair.
mysqli_stmt::$error is a property of the mysqli_stmt class, which is used to return the error message of the last mysqli_stmt query operation. If the query is executed successfully, the property will be empty. If an error occurs in the query, the property will return an error description. Through this property, we can capture error messages when MySQL executes statements.
// Example:use mysqli_stmt::$error Capture error message
if ($stmt->execute()) {
echo "Query successful!";
} else {
echo "error message: " . $stmt->error;
}
To automatically log database operation errors, you can create a simple error log system that will capture all database operation errors and log them into a log file. Here is a simple PHP example showing how to use mysqli_stmt::$error to catch and log database errors:
<?php
// Create a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check if the connection is successful
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// function:Log errors to log file
function log_error($message) {
$logFile = '/path/to/log/error_log.txt'; // Log file path
$date = date("Y-m-d H:i:s");
$logMessage = "[$date] - $message\n";
file_put_contents($logFile, $logMessage, FILE_APPEND);
}
// Prepare SQL Query
$query = "SELECT * FROM users WHERE id = ?";
$stmt = $mysqli->prepare($query);
if ($stmt === false) {
// if SQL 语句Prepare失败,Recording errors
log_error("SQL Prepare失败: " . $mysqli->error);
die("SQL mistake: " . $mysqli->error);
}
// 绑定参数并执行Query
$id = 1;
$stmt->bind_param("i", $id);
if (!$stmt->execute()) {
// ifQuery执行失败,Recording errors
log_error("Query执行失败: " . $stmt->error);
die("Query失败: " . $stmt->error);
}
// Get the results and process them
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// Output data
while ($row = $result->fetch_assoc()) {
echo "userID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "No data found";
}
// Close statements and database connections
$stmt->close();
$mysqli->close();
?>
Database connection : Use new mysqli() to connect to the database and check whether the connection is successful.
Logging function : The log_error() function appends error information to the specified log file.
SQL query execution : prepare SQL query through prepare() , bind_param() to bind parameters, execute execute() , and use mysqli_stmt::$error to record error information when execution fails.
Output result : If the query is successful, the result will be output; if no data is returned, "No data found".
In order to be able to monitor errors in database operations in real time, we can write error information to a log file, and we can obtain real-time error information by timely checking the log file. The following is an example of using PHP to read the error log and displaying error messages on the front end.
<?php
// Read log files in real time
function get_recent_errors($logFile) {
$errors = file_get_contents($logFile);
return nl2br($errors); // Convert line breaks to HTML Line break
}
$logFile = '/path/to/log/error_log.txt';
$recentErrors = get_recent_errors($logFile);
echo "<h2>最近的数据库操作mistake:</h2>";
echo "<pre>$recentErrors</pre>";
?>
Read log file : Read the contents of the log file through file_get_contents() .
Display error message : Display the contents in the log onto the page, convert the newline to HTML <br> tags through the nl2br() function to make it easier to read.
With the above method, you can easily catch and log errors in database operations using the mysqli_stmt::$error function in PHP. Combined with automatic error logging system and real-time monitoring, you can promptly discover and fix problems in database operations. This not only improves development efficiency, but also helps you respond quickly to system exceptions in a production environment.
In actual development, you can further expand the system as needed, such as notifying developers through email, recording error information using database, etc.