Question

I have the following class:

    <?php
    require 'config.php';
    ini_set('display_errors', 0);

    abstract class Conexion {

        protected $conexion;

        function __construct() {

        }

        function __destruct() {
            // $this->close();
        }

        protected function abrirConexion() {
            try {
                $this->conexion = new mysqli(BD_HOST, BD_USUARIO, BD_CLAVE, BD_BASEDEDATOS, BD_PUERTO, BD_SOCKET);
                if ($this->conexion->errno == 0) {
                    $this->conexion->query("SET NAMES utf8");
                    return true;
                } else {
                    $this->cerrarConexion();
                    return false;
                }
            } catch (Exception $e) {
                return false;
            }
        }

        protected function cerrarConexion() {
            $this->conexion->close();
        }

    }

and I want to catch the errors and exceptions that may occur in the execution of the script (exactly the connection to the database), and return true if all goes well, or false otherwise. But I could not catch connection errors (For example, when too many connections is generated, the script stops and does not return false). I read about set_handler_error, but I do not know how to implement it.

Can anyone help me?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top