As an alternative, you can always use a try ... catch. It would be something like this:
try {
$conexion = @mysqli_connect($servidor, $usuario, $password, $bd);
echo "Conexión efectuada.";
} catch (Exception $e) {
echo "La conexión no se pudo efectuar.";
exit();
}
The $e
object, which contains the exception if it has occurred, you can use it during your tests to see what has failed, or simply leave it there, unused. Do not ask for bread.
Good. I guess with "I'm positive" you mean that you get the message "Connection made." Depending on the PHP version and configuration, an error in mysqli_connect can be interpreted as a simple warning, which, by itself, does not throw an exception. Although I have taken this code from a website I had stored, it is true that it was quite old.
You can do two things:
1) Below the connection line, force the exception if you have not connected, like this:
try {
$conexion = @mysqli_connect($servidor, $usuario, $password, $bd);
if (!$conexion) throw new Exception();
echo "Conexión efectuada.";
} catch (Exception $e) {
echo "La conexión no se pudo efectuar.";
exit();
}
It's a fix, but it works to force the exception, even if only a warning is thrown.
The other alternative, which I like more, is to abandon the use of the mysqli extension and use PDO directly, like this:
try {
$conexion = new PDO('mysql:host='.$servidor.';dbname='.$bd.';charset=UTF8', $user, $pw);
echo "Conexión efectuada.";
} catch (Exception $e) {
echo "La conexión no se pudo efectuar.";
exit();
}
Working with PDO databases facilitates the performance of a DB and allows you to write a cleaner and maintainable code.
These last two options are tested with PHP 7.1.3 and running, with the standard configuration that mounts xampp by default. I hope you are useful.