You can't check $conn->errno
after connect, there is a special property $conn->connect_errno
for that.
Also in PHP, when you don't want any errors or warnings to be generated (e.g. because you don't care, or because you are handling them yourself like in your case), you are supposed to use the @
error control operator.
So it would look like this:
$this->conexion = @new mysqli(BD_HOST, BD_USUARIO, ...);
if ($this->conexion->connect_errno == 0) {
...
But that means you are doing the checks yourselves and you are not using exceptions at all! It's classic explicit error handling.
Now let's see how to make it work with exceptions like you wanted. The solution to that is to set mysqli error report mode properly:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
As explained in the documentation, this makes mysqli "throw mysqli_sql_exception
for errors instead of warnings". You don't need the @
operator then, neither the check for errno
value:
function abrirConexion() {
// This needs to be set just once.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$this->conexion = new mysqli(...);
$this->conexion->query("SET NAMES utf8");
return true;
} catch (Exception $e) {
return false;
}
}
Simple and clean.