Customize error messages when connecting to a database

3

Well here in the stack I found some topics that helped me, I'm new to PHP, and wanted to make my connection return a custom message without making it show those warnings .

But when I add verification nothing happens, my full code below.

<?php
class Connect {

    private $Connect;

    public function Connect() {
        $this->Connection();

        if(connection_aborted() == TRUE) {
            $this->Connection();
        }
    }

    public function Connection() {
        global $Config;

        $this->Connect = new mysqli($Config['mysql']['hostname'], $Config['mysql']['username'], $Config['mysql']['password'], $Config['mysql']['database'], $Config['mysql']['dataport']);

        if($this->Connect == false){
            exit('Falha na conexão, verifique Config.php');
        }

        return false;
    }
}
?>
    
asked by anonymous 26.04.2015 / 22:28

2 answers

3

You can customize the error message by transforming the errors returned by execptions with mysqli_report to avoid index-related warnings prefer: MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT instead of: MYSQLI_REPORT_ALL .

Add a try in the block where you want to throw the exception and use the catch to display the custom message, remember to implement a logging routine with the bank error to make it easier to detect errors.

public function __construct() {
    //linha que torna os erros em exceptions
    mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
    $this->Connection();

    if(connection_aborted() == TRUE) {
        $this->Connection();
    }
}

public function Connection() {

    global $Config;
    try {
        $this->Connect = new mysqli($Config['mysql']['hostname'],
                $Config['mysql']['username'], $Config['mysql']['password'],
                $Config['mysql']['database'], $Config['mysql']['dataport']);

    } catch (Exception $e) {
        exit('Falha na conexão, verifique Config.php');
    }

I prefer to define the constructor as a constructor and not depend on luck, as of php 5.3.3 the mechanism has changed. A method with the same name as the class within a namespace is not treated as a constructor.

Builders - manual

Prefer:

function __construct() {

Instead of:

public function Connect() {
    
26.04.2015 / 23:31
3

I recommend using PDO, since it is starting, it will make your life much easier. It supports more than 10 database types. An example of a connection with verification support is below:

<?php
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
        foreach($dbh->query('SELECT * from FOO') as $row) {
            print_r($row);
        }
       $dbh = null;
    } catch (PDOException $e) {
       print "Error!: " . $e->getMessage() . "<br/>";
       die();
    }
?>
    
26.04.2015 / 23:34