Simple Blog – Example 1: Structured

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

The first example of the Simple Blog application is developed using a structured programming style. Each page is self-contained having no dependency on external functions, libraries, or layout templates. As a result, the application’s content, presentation, and behavior layers are all meshed together and any layout, configuration, or functional changes will need to be applied to each and every page.

Now, from an end-user’s perspective, Simple Blog always looks and behaves identically so no sweat of their back if a password needs to be updated in a million places, but from a developer’s standpoint this approach presents a copy and paste nightmare. In the next example, Simple Blog – Example 2, we’ll clear up many of these problems using procedural programming, but for now, here’s the structured programming approach.

1. List

To display a list of all blog posts, the program has to perform two key tasks:

  1. Pull a listing of all blog posts from the database
  2. Loop through the database results and print each row as html.

Here’s the source code for each of these tasks:

1) Pull a listing of all blog posts from the database

	// Initialize database credentials
	$host = 'localhost';
	$user = 'blog';
	$password = 'secret';
	$dbname = 'blog';

	// Build database query
	$sql = 'select * from post';

	// Open database connection
	$connection = mysql_connect($host, $user, $password)
		or die(mysql_error());

	// Select target database
	mysql_select_db($dbname, $connection)
		or die(mysql_error());

	// Execute database query
	$result = mysql_query($sql, $connection)
		or die(mysql_error());

	// Initialize rows array
	$rows = array();

	// Fetch rows from database cursor
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$rows[] = $row;

	// Close database connection

Continue reading