So I usually use this structure to execute my queries on php, but the other day I was pointed out that it could be a bad practice.
Could anybody tell me why this is wrong and give me some tips on what should I do instead? I'm really looking to learn and improve my code.
Thanks in advance.
This practice is just awful. It's a bad heredity from the last century ways of writing code.
Instead, you have to add this line before connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
it will relieve you from the need of writing extra code for the every mysql call, as it will make mysqli to throw an Exception
in case of error automatically.
While exception itself is way better than regular error, as it can be caught and gracefully handled. Yet it will be converted into error, if not caught, which is again all right - because regular errors, depends on the site-wide settings, can be either shown on-screen or logged. Again without the need of writing a single line of extra code.
While developing, just have display_errors
setting on
and you will see all the errors the moment they occurred.
While on a live site, display_errors
have to be turned off
, but log_errors
have to be on
instead - and it will make your exception logged, for your future reference.