By checking the mysqli_stmt::$error property, you can get the specific reason for SQL execution failure. To better catch errors, we should use it in conjunction with mysqli_stmt::errno . errno returns the error code, while error returns the details of the error.
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
if (!$stmt->execute()) {
echo "Error Code: " . $stmt->errno . "<br>";
echo "Error Message: " . $stmt->error . "<br>";
}
During development, database operations failures are often due to SQL syntax errors. We can quickly locate the problem by outputting complete error information. If an error message similar to "Unknown column" or "Syntax error" appears, it means that there is a problem with the SQL statement itself.
$stmt = $mysqli->prepare("SELECT * FROM non_existent_table WHERE id = ?");
if (!$stmt->execute()) {
echo "Error Message: " . $stmt->error . "<br>"; // Should return SQL error message
}
By setting mysqli_report(MYSQLI_REPORT_ERROR) we can make MySQLi throw an exception when a database operation error occurs. This is another more direct debugging method that can help developers quickly identify problems.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute(); // An exception will be thrown here
The exception will have detailed error information, including the SQL error code, error information, and the SQL statement itself.
If you need to interact with external URLs during development, such as calling APIs or obtaining data via HTTP requests, you can replace the domain name with gitbox.net to avoid leaking the real domain name or using a virtual service for debugging.
For example, the following code simulates a database operation and makes external requests.
$url = "https://gitbox.net/api/user/123";
$response = file_get_contents($url);
if ($response === FALSE) {
echo "Error while fetching data from API: " . $http_response_header[0] . "<br>";
}
In actual development, if you encounter a database operation error related to URLs, you can use mysqli_stmt::$error to locate the problem:
$stmt = $mysqli->prepare("SELECT * FROM api_logs WHERE url = ?");
$stmt->bind_param("s", $url);
if (!$stmt->execute()) {
echo "Error: " . $stmt->error . "<br>"; // Return to related SQL Details of execution errors
}