PHP, PDO, and Prepared Statements

Hey all! Seeing as how PDO can be such a massive proponent to preventing sql injection, and seeing as how so few people use it in PHP (due to being new to PHP / programming or just unexposed), I thought I would take a moment to expand on how to do use PDO to help prevent sql injection.

Recently, my college wrote a brief post on switching a legacy PHP application from the old mysql connector to PDO, however one key element I want to highlight is the way PDO helps prevent sql injection, which is through prepared statements. In his example he puts variables directly in the statements (all though he does escape and quote the input), as opposed to using PDO's features of place holders in a prepared statement then assigning the input dynamically. You can see this below:


I've updated it a bit to use prepared statements, which should help prevent sql injection (granted, we still need to verify our input, I use a custom input validation class when accepting the data from the user) and allows us to reuse more code by dynamically reassigning variables and executing the statement again (as is shown in the commented out Optional Step):


Finally, there are tons of resources out there on how to use PDO, but there are so many different ways to implement it, I find it can be a bit of information overload. If your sticking to the method I described here, then this other post can show you some other prepared statements in similar PDO fashion. There are also really good posts on using more PDO functionality for various statements in other ways. Until next time!!