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
	mysql_close($connection);

  • First, initialize database credentials. This step will be repeated on each page.
  • Next we open a database connection and execute the database query. The basic open, select, execute, close steps will be repeated on each page.
  • Finally, we loop through the database results and build an array of posts
  • In the next example (Example 2: Procedural Programming), this code block will be reduced down to a single line of code.

2) Loop through the database results and print each row as html.


	<!DOCTYPE HTML>
	<html>

	<head>
	    <title>Simple Blog by Graeson Lewis</title>
	    <link rel="stylesheet" type="text/css" href="../css/styles.css" >
	<head>

	<body>

		<div class="container">

			<h1>Simple Blog</h1>
			<h3><a href="create.php">Add Post</a></h3><hr />

			<?php foreach($rows as $row): ?>

				<h4>
					<a href="read.php?id=<?php
						echo $row['id']; ?>"><?php
						echo $row['title']; ?></a>
				</h4>

				<p>
					<?php echo $row['content']; ?>
					<?php echo $row['created']; ?>
				</p>

			<?php endforeach; ?>

		</div>

	</body>

	</html>
	
  • First we declare the page header (title, styles, and h1). This step will be repeated on each page.
  • Next, we loop through the $rows array and print each post as HTML
  • Finally, we close our div, body, and html tags. This step will be repeated on each page.

2. Create

To create a new blog post, the program must perform 3 key tasks:

  1. Display an HTML form
  2. Process user input from form
  3. Save posted form data to a database table

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

1. Display an HTML form


	<!DOCTYPE HTML>
	<html>

	<head>
	    <title>Simple Blog by Graeson Lewis</title>
	    <link rel="stylesheet" type="text/css" href="../css/styles.css" >
	<head>

	<body>

		<div class="container">

			<h1>Simple Blog</h1><hr />

			<form method="POST" action="<?php
				echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">

				<p>
					<label for="title">Title</label><br />
					<input id="title" name="title" type="text" value="<?php
						echo htmlspecialchars($title);?>" autofocus/></p>

				<p>
					<label for="content">Content</label><br />
					<textarea id="content" name="content"><?php
						echo htmlspecialchars($content);?></textarea></p>

				<p>
					<input type="submit"/></p>

			</form>

		</div>

	</body>

	</html>

  • Notice how the header and footer tags are identical to the header and footer tags on the List page. These tags will be repeated on all pages.
  • First, the user inputs some data using the supplied textbox and textarea and submits the form.
  • Next, the page posts back to itself because the form’s action is set to $_SERVER[‘PHP_SELF’].
  • Finally, behind the scenes PHP builds the special $_POST array containing our user’s input.

2. Process user input from form


	// Initialize form values
	$title = NULL;
	$content = NULL;

	// Check for page postback
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {

		// Get user input from form
		$title = $_POST['title'];
		$content = $_POST['content'];

		// Sanitize user input
		$title = mysql_real_escape_string($title);
		$content = mysql_real_escape_string($content);

  • First, since the form submits to itself, we need a code block that will only be executed upon form submission. We accomplish this by wrapping the form processing and data access code in a conditional statement that checks for form submission.
  • Next, the user input is retrieved from the $_POST array
  • Finally, the user input is sanitized prior to data access.

3. Save posted form data to a database table


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

	// Build database query
	$sql = sprintf("insert into post (title, content) values ('%s', '%s')", $title, $content);

	// 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
	mysql_query($sql, $connection)
		or die(mysql_error());

	// Close database connection
	mysql_close($connection);

	// Redirect to site root
	header('Location:.');

  • Notice how the database credentials are identical to those on the list page.
  • Notice how the database operations connect, select, execute, and close are identical to those found on the list page.
  • First, we build our database insert statement using sprintf.
  • Next, we perform our basic database operations: connect, select, execute, and close
  • Finally, we redirect the user back to the List page

3. Read

To read a single blog post, the program must perform 3 key tasks:

  1. Retrieve the blog post’s id from the querystring
  2. Pull the blog post details from the database
  3. Display the blog post as HTML

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

1. Retrieve the blog post’s id from the querystring


	// Check the querystring for a numeric id
	if (isset($_GET['id']) && intval($_GET['id']) > 0) {

		// Get id from querystring
		$id = $_GET['id'];

		// Cast id to integer
		$id = (int) $id;
		
  • First, a conditional statement to ensure that the $_GET array has a key named id and said key has a numeric value.
  • Next, retrieve the id from the querystring.
  • Finally, sanitize the value before database access.

2. Pull the blog post details from the database


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

	// Build database query
	$sql = sprintf("select * from post where id = %d limit 1", $id);

	// 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());

	// Fetch row from database cursor
	$row = mysql_fetch_array($result, MYSQL_ASSOC);

	// Close database connection
	mysql_close($connection);

  • Notice that the database credentials are repeated again.
  • Notice that the basic database operations are repeated again.
  • First, build the database query using sprintf.
  • Next connect to the database and execute the database query
  • Finally, fetch the single row and close the connection

3. Display the blog post as HTML


	<!DOCTYPE HTML>
	<html>

	<head>
	    <title>Simple Blog by Graeson Lewis</title>
	    <link rel="stylesheet" type="text/css" href="../css/styles.css" >
	<head>

	<body>

		<div class="container">

			<h1>Simple Blog</h1><hr />

			<h3><?php echo $row['title']; ?></h3>

			<p>
				<?php echo $row['content']; ?>
				<?php echo $row['created']; ?><br />

				<a href="update.php?id=<?php echo $row['id']; ?>">Update</a>
				<a href="delete.php?id=<?php echo $row['id']; ?>"
					onClick = "javascript: return confirm
					('Are you sure you want to delete?');">Delete</a>
			</p>

		</div>

	</body>

	</html>

  • Notice how the header and footer tags are identical to the header and footer tags on the List page. These tags will be repeated on all pages.
  • First, since we’re only printing a single blog post, we don’t need a loop. So, we can simply print out our post’s title, content, and date created.
  • Next, we print HTML anchor tags which dynamically link to the blog post’s update and delete actions.

4. Update

To update a blog post, the program must perform 5 key tasks:

  1. Retrieve the blog post’s id from the querystring
  2. Pull the blog post details from the database
  3. Display an HTML form populated with the post’s details
  4. Process user input from the HTML form
  5. Save posted form data to a database table

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

1. Retrieve the blog post’s id from the querystring


	// Check the querystring for a numeric id
	if (isset($_GET['id']) && intval($_GET['id']) > 0) {

		// Initialize form values
		$title = NULL;
		$content = NULL;

		// Get id from querystring
		$id = $_GET['id'];

		// Cast id to integer
		$id = (int) $id;

  • The update page will be accesses with both get requests and post request, but regardless of request method the page should always have a valid id key/value in the querystring.

2. Pull the blog post details from the database


	// Check for initial page request
	if ($_SERVER['REQUEST_METHOD'] == 'GET') {

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

		// Build database query
		$sql = sprintf("select * from post where id = '%d' limit 1", $id);

		// 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());

		// Fetch row from dataset
		$row = mysql_fetch_array($result, MYSQL_ASSOC);

		// Close database connection
		mysql_close($connection);

		// Set form values
		$title = $row['title'];
		$content = $row['content'];
	}
	
  • If the page is accessed via get request, it’s being accessed for the first time; in other words, the request is not a postback.
  • First, we retrieve the post’s id from the querystring.
  • Next, we fetch the id’s title and content from the database
  • Finally, we populate the form with the values retrieved.

3. Display an HTML form populated with the post’s details


	<!DOCTYPE HTML>
	<html>

	<head>
	    <title>Simple Blog by Graeson Lewis</title>
	    <link rel="stylesheet" type="text/css" href="../css/styles.css" >
	<head>

	<body>

		<div class="container">

			<h1>Simple Blog</h1><hr />

			<form method="POST" action="<?php
				echo htmlspecialchars($_SERVER['REQUEST_URI']);?>">

				<p>
					<label for="title">Title</label><br />
					<input id="title" name="title" type="text" value="<?php
						echo htmlspecialchars($title); ?>" autofocus/></p>

				<p>
					<label for="content">Content</label><br />
					<textarea id="content" name="content"><?php
						echo htmlspecialchars($content);?></textarea></p>

				<p>
					<input type="submit"/></p>

			</form>

		</div>

	</body>

	</html>

4. Process user input from the HTML form


	// Check for page postback
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {

		// Get user input from form
		$title = $_POST['title'];
		$content = $_POST['content'];

		// Sanitize user input
		$title = mysql_real_escape_string($title);
		$content = mysql_real_escape_string($content);

5. Save posted form data to a database table


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

	// Build database query
	$sql = sprintf("update post set title = '%s', content = '%s' where id = %d", $title, $content, $id);

	// 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
	mysql_query($sql, $connection) or die(mysql_error());

	// Close database connection
	mysql_close($connection);

  • If the page request is a postback, we need to process the form.
  • First, retrieve the values of title and content from the $_POST array
  • Next, sanitize the user input before data access.
  • Next, save the user input to the database.
  • Finally, redirect the user to the List page

5. Delete

To delete a blog post, the program must perform 2 key tasks:

  1. Retrieve the blog post’s id from the querystring
  2. Delete the blog post from the database table

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

1. Retrieve the blog post’s id from the querystring


	// Check the querystring for a numeric id
	if (isset($_GET['id']) && intval($_GET['id']) > 0) {

		// Get id from querystring
		$id = $_GET['id'];

		// Cast id to integer
		$id = (int) $id;

2. Delete the blog post from the database table


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

	// Build database query
	$sql = sprintf("delete from post where id = %d limit 1", $id);

	// 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
	mysql_query($sql, $connection)
		or die(mysql_error());

	// Close database connection
	mysql_close($connection);

  • Notice, the delete action does not display any HTML.
  • First, retrieve the post’s id from the querystring.
  • Next, sanitize the retrieved value.
  • Next, perform the requested database operation.
  • Finally, redirect to the List page

Next

Cleaning house with Procedural Programming.
Simple Blog – Example 2

Download

You can download the source code for each example at box.net.
Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s