Current Location: Home> Latest Articles> Integrate the mysqli_stmt::$error output into your log system

Integrate the mysqli_stmt::$error output into your log system

gitbox 2025-05-28

Debugging errors in database operations is a crucial task when developing PHP applications. mysqli_stmt::$error is a very useful tool that helps developers catch error messages that may occur when executing SQL statements. To better track and debug these errors, it is very effective to integrate the error information of mysqli_stmt::$error into the log system.

In this article, we will explain how to combine mysqli_stmt::$error error output with the log system, so that you can easily record error information during database operations and track problems when problems occur.

1. Understand the mysqli_stmt::$error error property

mysqli_stmt::$error is a property of the mysqli_stmt class, indicating the error message encountered when executing SQL statements. You can access the error message returned by MySQL through this property. For example, if you execute an SQL query and an error occurs, you can get specific error information through this property.

 $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);

if (!$stmt->execute()) {
    // Output error message
    echo "Error: " . $stmt->error;
}

In the above code, if the SQL query execution fails, $stmt->error will contain a detailed description of the MySQL error. To ensure better error logging, we will pass these error messages to the log system.

2. Create a simple logging system

In order to write error information to the log, we first need to have a simple logging system. We can create a Logger class to manage all log writes. This class will be responsible for writing error information into a specified log file.

 class Logger {
    private $logFile;

    public function __construct($logFile) {
        $this->logFile = $logFile;
    }

    public function log($message) {
        $date = date('Y-m-d H:i:s');
        file_put_contents($this->logFile, "[$date] $message\n", FILE_APPEND);
    }
}

This Logger class adds a log message to the specified log file and contains a timestamp. Next, we will capture database operation errors through the mysqli_stmt::$error property and log these errors to the log.

3. Capture database errors and write to log

Now we can use the Logger class to write error information from database operations to the log. Assuming we have established a database connection and are ready to execute the query, we can use Logger to log the error when it occurs.

 $mysqli = new mysqli('localhost', 'user', 'password', 'database');
$logger = new Logger('/path/to/your/logfile.log');

$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);

if (!$stmt->execute()) {
    // Catch errors and write to log
    $errorMessage = "MySQL Error: " . $stmt->error;
    $logger->log($errorMessage);

    // You can choose to display error messages,Or other ways to deal with errors
    echo "An error occurred. Please check the logs for details.";
}

In the above code, we try to perform a query operation. If the query fails, the error message will be captured by mysqli_stmt::$error and passed to the log method of the Logger class and written to the log file.

In this way, you can easily log all database errors into the log file and quickly locate the problem if it occurs.

4. Improve logging: Add more information

To improve log availability, you can also add more context information when logging error messages. For example, you can record the specific time of executing the SQL statement, the SQL statement itself, and the error file and line number, and other information. This will help to better understand the cause of the error during the debugging process.

 class Logger {
    private $logFile;

    public function __construct($logFile) {
        $this->logFile = $logFile;
    }

    public function log($message) {
        $date = date('Y-m-d H:i:s');
        file_put_contents($this->logFile, "[$date] $message\n", FILE_APPEND);
    }

    public function logError($stmt, $sql) {
        $errorMessage = "MySQL Error: " . $stmt->error;
        $errorDetails = [
            'timestamp' => date('Y-m-d H:i:s'),
            'error_message' => $errorMessage,
            'sql' => $sql,
            'file' => debug_backtrace()[0]['file'],
            'line' => debug_backtrace()[0]['line']
        ];
        $this->log(json_encode($errorDetails));
    }
}

$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);

if (!$stmt->execute()) {
    // Record detailed error information
    $logger->logError($stmt, "SELECT * FROM users WHERE id = $user_id");
    echo "An error occurred. Please check the logs for details.";
}

By recording detailed error information, including executed SQL statements, file names, and line numbers, you can track errors more easily and locate issues quickly.