Database operations are required in just about any project of mine. So, I wrote up a simple PHP class that performs all your basic CRUD operations using PDO and MySQL prepared statements. Using it reduces my setup time, provices basic application security, and makes development a breeze.
The constructor of the class creates your PDO object using the MySQL driver. I also set a few options to prevent strange “gotchas” and determine the behavior of queries. The rest of the class contains methods that perform your CRUD operations: SELECT, INSERT, UPDATE, and DELETE. Each method takes two params, a SQL query and an associative array of parameters to bind.
SELECT queries will return the data as an associative array, which is great for quickly encoding as JSON to ouptut. INSERT and other queries will return the number of rows affected. Any errors or exceptions will be caught and the method will return false. To differentiate between an empty result and an error, just use === for strict type checking.
Here’s an example of the class in action:
Check out the source code below, or view the Gist on GitHub.