Database interaction is a key component when developing PHP projects, especially large projects. In such projects, ensuring the security and stability of data operations is crucial. The mysqli extension provides a series of functions and methods for interacting with a MySQL database. The mysqli_stmt::$error function is a very useful tool that helps developers catch errors when executing SQL statements.
In this article, we will explain how to use mysqli_stmt::$error effectively for error handling through actual case analysis, and share some optimization experience to help developers improve the robustness and maintainability of their code.
The mysqli_stmt::$error function is a property in the mysqli_stmt class that returns an error message associated with the currently prepared statement. If an error occurs when performing operations such as prepare , bind_param or execute , mysqli_stmt::$error will return an error message. This is very useful for catching and handling database errors.
<?php
// Create a database connection
$mysqli = new mysqli("localhost", "user", "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 email = ?");
// 检查PrepareStatement是否成功
if ($stmt === false) {
echo "Error preparing statement: " . $mysqli->error;
exit();
}
// Bind parameters
$email = "[email protected]";
$stmt->bind_param("s", $email);
// 执行Statement
$stmt->execute();
// Check whether the execution is successful
if ($stmt->error) {
echo "Execution error: " . $stmt->error;
} else {
echo "Execution successful!";
}
// 关闭Statement和连接
$stmt->close();
$mysqli->close();
?>
In this example, we first create a connection to the database and then prepare a SQL query statement. When executing the preparation statement, we checked for errors to occur. mysqli_stmt::$error can help us catch errors during statement execution and further process them according to error messages.
In large projects, database operations are usually the core part of the system, involving a large number of queries, inserts, updates, and delete operations. Therefore, error handling is not just a debugging tool, it directly affects the stability and user experience of the system.
In the project, we should try to avoid outputting database errors directly to the end user. Instead, error messages should be logged into a log file so that developers can troubleshoot based on the log.
<?php
// Error logging function
function log_error($message) {
// Write error information to log file
file_put_contents('error_log.txt', date('Y-m-d H:i:s') . " - " . $message . PHP_EOL, FILE_APPEND);
}
// Database connection
$mysqli = new mysqli("localhost", "user", "password", "database");
// Check if the connection is successful
if ($mysqli->connect_error) {
log_error("Connection failed: " . $mysqli->connect_error);
die("Database connection error.");
}
// SQL StatementPrepare
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
// StatementPrepare失败时,Recording errors
if ($stmt === false) {
log_error("Error preparing statement: " . $mysqli->error);
exit();
}
// Bind parameters
$email = "[email protected]";
$stmt->bind_param("s", $email);
// 执行Statement并检查错误
$stmt->execute();
if ($stmt->error) {
log_error("Execution error: " . $stmt->error);
echo "An error occurred, please try again later.";
} else {
echo "Execution successful!";
}
// Close the resource
$stmt->close();
$mysqli->close();
?>
In this code, we add logging functionality to error capture. All error messages will be written to the error_log.txt file and will not be directly exposed to the user. This can not only avoid leaking sensitive information, but also help developers quickly locate problems.
In some high-traffic systems, excessive error checking may affect system performance. In order to improve performance, we can reduce the frequency of error checks based on the specific situation. For example, when executing multiple SQL queries in batches, we can centrally check for errors instead of doing separate error handling for each query.
<?php
$queries = [
"SELECT * FROM users WHERE email = ?",
"SELECT * FROM products WHERE id = ?"
];
$mysqli = new mysqli("localhost", "user", "password", "database");
// Check the connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute query in batches
foreach ($queries as $query) {
$stmt = $mysqli->prepare($query);
if ($stmt === false) {
log_error("Error preparing statement: " . $mysqli->error);
continue; // If a query fails,Skip to continue executing other queries
}
// 执行其他Bind parameters和查询的操作
$stmt->execute();
if ($stmt->error) {
log_error("Execution error: " . $stmt->error);
}
$stmt->close();
}
$mysqli->close();
?>
In large projects, using mysqli_stmt::$error for error handling can not only improve the stability of the code, but also effectively reduce the risk of crashes at runtime. Here are some best practice suggestions:
Logging : Log error information into a log file instead of directly displaying it to the user.
Centralized Error Handling : Especially when executing multiple SQL queries, you can reduce performance overhead by centrally checking for errors.
Avoid excessive error checking : Reasonably evaluate whether error checking is required for every database operation to avoid unnecessary performance waste.
Through these methods, we can ensure more efficient and safe use of mysqli_stmt::$error in large PHP projects and improve overall quality and maintainability of the project.