'Cannot show an error message after creating an error [duplicate]
I'm trying to connect to the database using localhost.
<?php
//Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
// Create a connection
$conn = mysqli_connect($servername, $username, $password);
// Die if connection was not successful
if (!$conn){
die("Sorry we failed to connect: ". mysqli_connect_error());
}
else{
echo "Connection was successful";
}
?>
It works if the connection is made but I don't get the "Sorry we failed to connect" message when I intentionally create an error.
What could be the potential causes of this?
Solution 1:[1]
As stated in the documentation:
If MYSQLI_REPORT_STRICT is enabled and the attempt to connect to the requested database fails, a mysqli_sql_exception is thrown.
Since you are getting an exception, this must be set. Your code should change as follows in this case:
try {
$conn = mysqli_connect($servername, $username, $password);
} catch(mysqli_sql_exception $e) {
die("Sorry we failed to connect: ". mysqli_connect_error());
}
echo "Connection was successful";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D B |
