How to create Exceptions to treat statement with Mysqli

3

I'm migrating from PDO to Mysqli and when doing some operation with the bank, the check block was like this:

$query = $db->prepare("ppapapa sql sql");

try {
        $query -> execute();
        return $query -> fetchAll();

    } catch(PDOException $e) {
        die($e -> getMessage());
    }

How would this error handling with Mysqli be?

    
asked by anonymous 18.10.2015 / 13:44

2 answers

4

You need to enable exceptions with:

mysqli_report(MYSQLI_REPORT_ALL);

Or just:

mysqli_report(MYSQLI_REPORT_STRICT);

Then you can usually use:

$query = $db->prepare("ppapapa sql sql");

try {
    $query -> execute();
    return $query -> fetchAll();
} catch(mysqli_sql_exception $e) {
    die($e -> getMessage());
}

Documentation for mysqli_report .

If you do not want to do this you can treat the errors individually:

if (!mysqli->query($insadquery)) {   
    die(mysqli->errno . " - " . $mysqli->error); 
}

Often this form is preferred.

All mysqli documentation.

    
18.10.2015 / 14:31
3

The function that makes errors in exceptions in MySQLi is to use the function mysqli_report () .

Because MySQLi is a specialized API, it has some interesting features, such as detecting common errors in the prepare() method. some of them are:

Virtually all of them are typos or some poorly formatted value.

1146 # Table 'nome' doesn't exist
1054 # Unknown column 'nome' in 'clause'
1064 # You have an error in your SQL syntax;

To catch these errors use the combination of MYSQLI_REPORT_STRICT and MYSQLI_REPORT_ERROR and leave prepare() within catch. Other errors such as foreign key violation or ids repetition are checked against execute() .

mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ERROR);

try {
    $query = $db->prepare("ppapapa sql sql");
    $query -> execute();
    $result = $query->get_result();
    return $result->fetch_all();
}catch(mysqli_sql_exception $e) {
    echo 'SQLState: '. $e->getCode() .' # '. $e->getMessage();
}

When to use MYSQLI_REPORT_ALL ?

MYSQLI_REPORT_ALL should be used for debugging and bottleneck identification, if a query does not use the index, an exception will be thrown that will deflect the stream even though no true error occurred, which is quite indigest for a system already in production.

Example of this exception .

  

No index used in query / prepared statement SELECT * FROM ...

MYSQLI_REPORT_ALL or MYSQLI_REPORT_INDEX provide good clues about why some queries are slow, use where appropriate.

    
18.10.2015 / 17:40