In PHP development, database operations are among the most common tasks. When interacting with databases, especially using the MySQLi extension, capturing and logging errors is crucial for debugging and maintaining your applications. MySQLi provides the mysqli::$errno and mysqli::$error properties to help developers understand the specific causes of database errors.
This article will explain how to use mysqli::$errno for effective error logging, helping developers better handle potential issues during database connections and operations.
mysqli::$errno is a property of the MySQLi class that stores the error code from the most recent database operation that failed. This error code is an integer value used to identify the specific type of error. mysqli::$errno only holds a meaningful value when an error occurs; otherwise, it will be 0.
Additionally, the mysqli::$error property contains a detailed description of the error (the error message). Using these two properties together allows developers to accurately diagnose problems.
The error codes for mysqli::$errno are predefined. Here are some common codes and their meanings:
1045: Authorization error when accessing the database (e.g., incorrect username or password).
2002: Connection failed, usually because the database host is unreachable.
1146: Table does not exist.
1064: SQL syntax error.
In practice, besides catching errors, we often need to log them for future reference and analysis. The following example demonstrates how to log errors using mysqli::$errno and mysqli::$error:
<?php
// Configure database connection parameters
$host = 'localhost';
$user = 'root';
$password = 'password';
$dbname = 'test_db';
<p>// Create a database connection<br>
$conn = new mysqli($host, $user, $password, $dbname);</p>
<p>// Check if the connection was successful<br>
if ($conn->connect_error) {<br>
// Log connection error<br>
error_log("Connection failed: " . $conn->connect_error, 3, 'errors.log');<br>
exit();<br>
}</p>
<p>// Execute a query<br>
$sql = "SELECT * FROM non_existent_table";<br>
$result = $conn->query($sql);</p>
<p>// Check if the query was successful<br>
if (!$result) {<br>
// If the query fails, log the error message and code<br>
error_log("Error: " . $conn->errno . " - " . $conn->error . "\n", 3, 'errors.log');<br>
}</p>
<p>// Close the connection<br>
$conn->close();<br>
?>
In this example, we first attempt to connect to the database. If the connection fails, the connection error is logged to the errors.log file. Then, we execute a query to retrieve data from a non-existent table. If the query fails, we capture the error message and log both the error code and message.
In a production environment, error logs should include timestamps to facilitate tracking and troubleshooting. You can add the current time to each log entry as follows:
<?php
// Get the current time
$date = date('Y-m-d H:i:s');
<p>// Execute the query and log errors with timestamps<br>
if (!$result) {<br>
// Include timestamp in the log<br>
error_log("[$date] Error: " . $conn->errno . " - " . $conn->error . "\n", 3, 'errors.log');<br>
}<br>
?>
By including the current time in each error log entry, developers can clearly see when each error occurred, aiding in more precise troubleshooting.
Over time, error log files can become very large, affecting system performance and maintainability. Regularly cleaning and archiving error logs is therefore important. Here are some strategies to optimize log management:
Regular archiving and cleaning: Set scheduled tasks to archive error logs and remove old files.
Log rotation: Use tools like logrotate to automatically manage log file sizes.
Tiered logging: Record logs at different levels (info, warning, error) based on the severity of the error.
Using mysqli::$errno and mysqli::$error, PHP developers can easily capture and log database errors. By combining timestamps with log file management and cleanup strategies, error logging can be recorded and optimized effectively. These measures help developers quickly identify issues during development and testing and provide valuable clues for troubleshooting in production environments.
This guide aims to help you understand how to effectively use mysqli::$errno for error logging and apply it in real-world PHP development, improving both code robustness and maintainability.