How do I display a MySQL error in PHP for a long query that depends on the user input?
To display a MySQL error in PHP for a long query that depends on user input, you can use the mysqli_error()
function. This function returns a string description of the last error.
Here's an example of how you can use it:
<?php
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);
if (!$result) {
// query failed
$error = mysqli_error($conn);
echo "Error: $error";
} else {
// query was successful
// do something with the data
}
In this example, $conn
is a connection to the MySQL database that was created using mysqli_connect()
. If the query fails, the mysqli_error()
function will return a string describing the error, which can then be displayed to the user.
It's important to note that you should not display raw MySQL errors to the user, as they may contain sensitive information. Instead, you should display a generic error message to the user, and log the full MySQL error message for debugging purposes.