Manually Displaying MySQL Error Messages for Dynamic Queries in PHP
In PHP, when executing long MySQL queries that incorporate user input, it's essential to handle potential errors. The default error message, "Query Failed," provides minimal insight into the underlying issue. This article explains how to display the precise error message on the web page.
To begin, let's consider your provided code:
$query = "SELECT ...."; if (!$this->result) { printf("Query failed: %s\n", mysqli_connect_error()); exit; }
In this code, you're printing the connection error message instead of the specific query failure message. To rectify this, modify the if condition to print the query failure message instead:
if (!$this->result) { printf("Query failed: %s\n", mysqli_error($this->db_link)); exit; }
Furthermore, for more detailed error handling, you can utilize the mysqli_query() function. This function returns 0 if an error occurs. You can use mysqli_error() to retrieve the error message:
mysqli_query($this->db_link, $query) or die(mysqli_error($this->db_link));
Additionally, you can display the error code using mysqli_errno():
echo mysqli_errno($this->db_link);
By implementing these suggestions, you can effectively display MySQL error messages for dynamic queries and provide valuable information for troubleshooting purposes.
The above is the detailed content of How Can I Display Precise MySQL Error Messages for Dynamic Queries in PHP?. For more information, please follow other related articles on the PHP Chinese website!