"changing from mysqli to pdo" Code Answer


first off, let me congratulate you for going with pdo. out of all the experienced php developers i know, it's near unanimous that they prefer pdo to mysqli.

i highly recommend you read through this guide to using pdo. it should answer all your questions and even answer a few you will likely have in the future.

to your specific questions:

no you do not need to escape anything anymore, so long as you are using prepared statements with placeholders. escaping existed exactly because people were interpolating variables into sql statements and that could confuse the quoting you needed to enclose strings.

with prepared statements that issue no longer exists, which also means that there is no longer the danger of sql injection. sql injection takes advantage of string concatenation to transform the original sql statement into an entirely different one, again using quotes, which is why a non-escaped string accepted from user input was the attack vector for sql injection. both problems are solved using parameters and prepared statements.

as for error handling with pdo, you want to utilize pdo::errmode_exception which is discussed in the manual here.

unfortunately, the default for pdo is pdo::errmode_silent which essentially ignores database errors and just sets pdo object variables you would have to check yourself.

with that said, you can fix this by adding the error mode when you create the pdo connection object or just afterwards. examples are on the pdo error mode page i linked.

as for try-catch blocks, in general an exception is not something you want to catch specifically unless you have some functional code to work around the error. wrapping every sql call just so you can report an error message is bad, both from the point of view of dry as well as being an anti-pattern. with the proper error mode, sql errors will throw exceptions that you can handle in your error handler, and in general are things you shouldn't be eating up and continuing on from.

your error handler should be (in production) logging the error to disk/emailing a sysadmin or site owner, and displaying a professional looking non-specific error message informing the user of the problem and that should be happening for all exceptions.

By Dave Johnson on April 10 2022

Answers related to “changing from mysqli to pdo”

Only authorized users can answer the Search term. Please sign in first, or register a free account.