In modern PHP development, error tracing and logging are important links to improve application stability and performance. Especially when interacting with a database, accurately logging and tracking SQL errors is critical to debugging and maintenance. In this article, we will explain how to use the mysqli_stmt::$error function in conjunction with the PSR logging standard for more efficient error tracking and logging.
mysqli_stmt::$error is a method provided by the mysqli extension in PHP to get the error of the current SQL statement. When we execute SQL query, if an error occurs, we can use this property to get the error information returned by the database.
For example, suppose we encounter an error when executing a prepared statement:
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
if (!$stmt->execute()) {
echo "Error: " . $stmt->error;
}
In this example, if an error occurs in the SQL query, $stmt->error will return an error message, helping developers quickly locate the problem.
PSR (PHP Standard Recommendation) logging standard is an interface standard used in the PHP ecosystem to unify logging. PSR-3 is the standard for PHP logging. It defines a logging interface, so that different log libraries (such as Monolog, Log4php, etc.) can implement this interface, so that a unified logging method is used in the code.
The simple usage of a PSR-3 log interface is as follows:
use Psr\Log\LoggerInterface;
class MyApp
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function someMethod()
{
// Logging
$this->logger->error('Something went wrong!');
}
}
PSR-3 provides log-level methods such as debug() , info() , notice () , warning () , error () , critical () , alert() , and emergency() to help developers record different types of log information according to the severity of the problem.
Now, we will show how to use mysqli_stmt::$error in conjunction with the PSR log standard to more efficiently log error messages when database operations fail.
First, we need to install a log library that supports the PSR-3 standard. Here we take Monolog as an example:
composer require monolog/monolog
Next, we will configure Monolog Logger and integrate it with the PSR-3 interface:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('my_logger');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::ERROR));
Now, suppose we have a function that interacts with the database, we can log the error message in mysqli_stmt::$error to the log:
function fetchData($mysqli, $userId, Logger $logger)
{
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
if (!$stmt) {
$logger->error("SQL prepare failed: " . $mysqli->error);
return false;
}
$stmt->bind_param("i", $userId);
if (!$stmt->execute()) {
$logger->error("SQL execution failed: " . $stmt->error);
return false;
}
$result = $stmt->get_result();
return $result->fetch_all(MYSQLI_ASSOC);
}
In this example, when a database operation fails, the error message will be logged into the specified log file and contains a detailed error description. This allows developers to easily track SQL errors and troubleshoot.
The PSR-3 standard also allows us to log context information in the log to help better analyze errors. For example, we can use the user's ID or other problem information that helps diagnose as context parameters of the log:
$logger->error('SQL execution failed', [
'error' => $stmt->error,
'user_id' => $userId,
'query' => $stmt->sqlstate,
]);
This will record richer error information, including user ID and SQL error codes, helping us locate issues more accurately.
By using the mysqli_stmt::$error function in conjunction with the PSR log standard, we can efficiently log errors in database operations and ensure the consistency and ease of use of logs. Whether it is a development environment or a production environment, error logs are an important tool for us to quickly locate and solve problems. The flexibility and compatibility provided by the PSR logging standard enables us to use any standard-compliant log library without worrying about specific implementation details.
With such a technology stack, we can achieve more efficient error tracking and recording, thereby improving application stability and development efficiency.