Debugging and data tracking are important when developing PHP projects, especially when interacting with databases. If you need to debug the results of MySQL queries or track database operations, recording the output of the mysqli_result function will help you better understand the execution of the program.
In this article, we will introduce how to use the logging function to record the output content of each call to mysqli_result , for subsequent debugging and analysis.
First, we need to prepare a log file to record the output of each query. PHP provides a very convenient logging method. Using the error_log function, we can write information to a specified file.
$logFile = 'mysqli_debug.log';
Next, we will encapsulate the output function of mysqli_result to ensure that the relevant information can be recorded every time the function is called. Suppose we already have a mysqli connection and a query execution process.
// Custom functions to record mysqli_result Output
function log_mysqli_result($result) {
global $logFile;
// Get the content of the result set
$output = '';
while ($row = $result->fetch_assoc()) {
$output .= json_encode($row) . "\n";
}
// Get the current time
$date = date('Y-m-d H:i:s');
// Logging
$logMessage = "[$date] Query Result: \n$output\n";
file_put_contents($logFile, $logMessage, FILE_APPEND);
}
Now, we will call the log_mysqli_result function after executing the query to record the result of the query. Suppose we want to execute a simple SELECT query.
// Database connection
$mysqli = new mysqli("m66.net", "username", "password", "database");
// Check if the connection is successful
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute a query
$query = "SELECT * FROM users WHERE status = 'active'";
$result = $mysqli->query($query);
// Check whether the query is successful
if ($result) {
// Record query results
log_mysqli_result($result);
} else {
echo "Query failed: " . $mysqli->error;
}
// Close the connection
$mysqli->close();
The log file mysqli_debug.log will record the output content of each query. You can view this file to track the output after each call to mysqli_result .
For example, a log file might contain the following:
[2025-05-05 12:30:00] Query Result:
{"id":1,"name":"John Doe","status":"active"}
{"id":2,"name":"Jane Smith","status":"active"}
[2025-05-05 12:45:00] Query Result:
{"id":3,"name":"Alice Johnson","status":"active"}
In this way, you can clearly see the results of each query and can be easily used for debugging and data tracking.
Summarize
This article shows how to encapsulate the mysqli_result function through PHP and combine logging to help developers track the output content of database queries. In this way, debugging and data tracking will become more convenient and effective. I hope this article can provide you with some useful tips to help you improve your development efficiency.