Simple Blog – Example 6: PDO

Simple Blog is a multi-part series. Check out The Index

In the last example, Simple Blog – Example 5, we rewrote the application’s data logic using PHP’s mysqli extension. In this example, we’ll rewrite the application’s data logic again, but this time using PHP Data Objects. PDO offers significant advantages over PHP’s original mysql extension.

First, PDO offers a fully object-oriented interface through its PDO, PDOStatement, and PDOException classes. Second, PDO helps protect our application from SQL injection attacks by using parameterized statements. Third, PDO offers transactional support to commit or rollback multiple statements at once. Finally, PDO offers a consistent interface across multiple database drivers which greatly enhances the portability of our application.

Database Class

Since PDO already offers an object oriented interface, I decided not to write a wrapper class. The new Database class extends the PDO class and performs the simple task of connecting to the database engine and selecting the target database.

class Database extends PDO 
{
	public function __construct() 
	{	    
	    try 
	    {
	   		// Build PDO data source name for MySQL connection
		    $dsn = "mysql:host=".DATABASE_HOST.";dbname=".DATABASE_NAME;

		    // Open database connection
			parent::__construct($dsn, DATABASE_USER, DATABASE_PASSWORD);	
		}
		catch (PDOException $exception) 
		{
			die($exception->getMessage());
		}
	}
}

Continue reading