How to display mysqli_query errors
✔ Recommended Answer
Since PHP 8.1, the default setting for mysqli error reporting is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT
, which causes errors to throw an exception instead of just returning false
.
If you want to check for errors in your code instead of getting exceptions, use
mysqli_report(MYSQLI_REPORT_OFF);
A better solution would be to use an exception handler.
if ($conn) { $sql = "INSERT INTO tbl_users (userId, email, pass) VALUES ('$userId', '$email', '$pass')"; try { mysqli_query($conn, $sql); echo json_encode(array( "status" => "Ok", "message" => "Success", )); catch (mysqli_sql_exception $e) { echo json_encode(array( "status" => "Error", "message" => $e->getMessage() )); }}
Source: stackoverflow.com
Answered By: Barmar
To display mysqli_query
errors in PHP, you can use the mysqli_error()
function. This function returns a string containing the last error message from the most recent mysqli
function call, including mysqli_query
.
Here is an example:
php// Create a connection to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check if the connection was successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a query
$query = "SELECT * FROM non_existent_table";
$result = mysqli_query($conn, $query);
// Check if the query was successful
if (!$result) {
die("Query failed: " . mysqli_error($conn));
}
In this example, if the query fails, the mysqli_error()
function will return a string containing the error message, which will be displayed using the die()
function. You can modify this to display the error message in a different way if you prefer.
Comments
Post a Comment