Simple Blog – Example 5: MySQLi

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

Until now we’ve been exploring different programming styles. We programmed the Simple Blog application using structured, procedural, and object oriented programming. Next, we explored the MVC pattern by physically separating our data, application, and presentation logic. So far, each example has required pervasive changes to the application. For the next few examples, however, we’ll focus on improving specific layers of the application, rather than rewriting the application as a whole.

In this example we’ll be revisiting Simple Blog’s data access layer. PHP offers three options for interacting with a MySQL database: mysql, mysqli, and pdo. So far, we’ve only used the original mysql interface. So, let’s rewrite the Database and Post classes using mysqli. The two mysqli benefits I’m most interested in are the object-oriented interface and the support for prepared statements.

Database Class

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

class Database extends mysqli 
{
	private $hostname;
	private $username;
	private $password;
	private $database;
	
	public function __construct() 
	{
		// Initialize object with database constants
		$this->hostname = DATABASE_HOST;
		$this->username = DATABASE_USER;
		$this->password = DATABASE_PASSWORD;
		$this->database = DATABASE_NAME;	
		
	    // Open database connection
		parent::__construct(
			$this->hostname, 
			$this->username, 
			$this->password, 
			$this->database
			);
	}

}

Continue reading