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.