Handling Entries for a Blogger Built with PHP

Are you searching for an accessible guide on how to create a blog application with PHP 5? Then this set of articles might be what you’ve been looking for! Welcome to the second part of the series “Building a Blogger with PHP.” In three parts, this series demonstrates in a few easy steps how to build a classic blog application in PHP 5 by following an object-oriented approach.

Stepping back for a moment to the first installment of the series, I’m certain you’ll recall that the basic structure of the blogger in question was created by using a single class, which was originally named “BlogProcessor.” Also, it should be fresh in your mind that I defined some handy methods to perform specific tasks, such as inserting, updating and deleting blog entries from the corresponding “blogs” database table that I created previously. Now, does all this sound familiar to you? I hope it does.

While all the methods that I mentioned above were specifically created for handling potential database entries, in conjunction with existing blog data, there’s still one aspect of the application that needs to be appropriately covered. Thus, I’m sure that you’re wondering…what is it?

Well, as you’ll remember from the previous article, the blogger wasn’t yet capable of displaying all the entries on the browser, and also wasn’t able to show the corresponding online forms for adding and updating blog data.

Therefore, in this second installment of the series, I’ll show you how to expand the initial functionality of the already familiar “BlogProcessor” class so that it is capable of addressing all these issues.

Are you ready to take the next step in developing a blogger with PHP 5? Let’s do it together!

{mospagebreak title=Defining the displayBlogs() method}

Prior to extending the existing functionality of the “BlogProcessor” class that you learned in the first article, I’d like to show its original signature so you will remember how it looked. Having said that, here is the definition of this class as it was initially created:   

// define ‘BlogProcessor’ class
class BlogProcessor{
            private $mysql;
            private $blogData;
            public function __construct(MySQL $mysql){
                        $this->mysql=$mysql;
                        $this->blogData=$_POST;
            }
            // display blog system
            public function displayBlogger(){
                        // edit blog
                        if($this->blogData['editblog']){
                                   // code for displaying edit page goes here
                        }
                        else{
                                   // insert new blog
                                   if($this->blogData['insertblog']){
                                               $this->insertBlog();
                                   }
                                   // update blog
                                   elseif($this->blogData['updateblog']){
                                               $this->updateBlog();
                                   }
                                   // delete blog
                                   elseif($this->blogData['deleteblog']){
                                               $this->deleteBlog();       
                                   }
                        }
                        // code for displaying main page goes here
            }
            // insert new blog
            private function insertBlog(){
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("INSERT INTO blogs
(id,author,title,content,date) VALUES (NULL,’$author’,’$title’,’$content’,TIMESTAMP
(10))");
                        header(‘Location:’.$_SERVER['PHP_SELF']);
            }
            // update blog
            private function updateBlog(){
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("UPDATE blogs SET
title=’$title’,author=’$author’,content=’$content’,date=TIMESTAMP(10) WHERE
id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);
            }
            // delete blog
            private function deleteBlog(){
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("DELETE FROM blogs WHERE id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);
            }
}

As you’ll recall, the above class was only capable of performing some limited tasks, such as adding new entries to the “blogs” database table, and updating/removing existing ones. However, as I said in the beginning, the referenced class must also be capable of doing many more things, like displaying the complete list of entries stored on the corresponding database.

In response to these requirements, below I appended a new method to the class which shows the entire set of blog entries, in conjunction with a pair of buttons for updating and deleting each blog in question. Thus, have a look at this brand new method, please:

// display all the blogs
private function displayBlogs(){
    $result=$this->mysql->query("SELECT * FROM blogs");
    $output=”;
    while($row=$result->fetchRow()){
        $content=nl2br($row['content']); 
$output.=<<<EOD
<div class="blog">
<h2>$row[title]</h2>
<h3> Author: $row[author]<h3>
<h3> Posted: $row[date]</h3>
<p>$content</p>
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="submit" value="Edit Blog" name="editblog" />
<input type="submit" value="Delete Blog" name="deleteblog" />
<input type="hidden" value="$row[id]" name="id" />
</form>
</div>
EOD;
    }
    return $output;
}

If you examine the source code that corresponds to the above method, you’ll agree that its definition is really simple. In short, all that this method does is fetch all the entries stored on the respective database table and display them on the browser. Also, you should notice the inclusion of the two control buttons that I mentioned before, which come in useful for updating and deleting a particular entry.

With reference to these controls, you’ll realize that each time one of them is clicked, the corresponding form that wraps them is submitted to itself. Certainly, this condition can be easily checked inside the blog processor class to trigger the respective processes for removing or eventually updating blog entries.

In the next few lines I’ll add another handy method to the blog processor, which will be responsible for showing the corresponding online form where users can insert a new blog entry into the database table for further display.

To see how this new method will be defined, click on the link that appears below and keep reading.

{mospagebreak title=Defining the displayInsertForm() method}

As I explained in the previous section, the next few lines will be entirely focused on showing how to create a new class method for displaying the respective online form where users can add new blog entries that will be shown on the application’s main page.

Given that, here is the definition of this useful method, which I named “displayInsertForm().” Its signature is as follows:

// display insertion form
private function displayInsertForm(){
            $output=<<<EOD
<div class="dataform">
<h2>Insert New Blog</h2>
<form action="$_SERVER[PHP_SELF]" method="post" id="insertform">
<p>Title:</p><p><input type="text" name="title"
class="datafield" /></p>
<p>Author:</p><p><input type="text" name="author"
class="datafield" /></p>
<p>Type your content below</p><p><textarea
name="content"></textarea></p>
<p><input type="submit" name="insertblog" value="Insert
Blog" /></p>
</form>
</div>
EOD;
            return $output;  
}

In this case, the method listed above is simply tasked with rendering an input form which contains the typical boxes for entering basic blog data, such as the blog’s title, author and content.

As you can see, there’s nothing unexpected concerning the previous method, so let’s move on and see another one. This method will be aimed at displaying the respective online form that allows the updating of a particular blog entry.

The topic sounds really interesting, right? Therefore, go ahead and jump into the following section. I’ll be there, waiting for you.

{mospagebreak title=Creating the displayUpdateForm() method}

Following a similar approach to the one that I used for creating the insertion form that you learned about in the previous section, it’s possible to define another important method that belongs to the “BlogProcessor” class. This one displays the required online form for updating a specific blog entry.

This being said, the signature for this broadband new method, denominated “displayUdpateForm()” is the following:

// display update form
private function displayUpdateForm(){
            $id=$this->blogData['id'];
            $result=$this->mysql->query("SELECT * FROM blogs
WHERE id=’$id’");
            if($result->countRows()>0){
                        $row=$result->fetchRow();
$output=<<<EOD
<div class="dataform">
<h2>Update Blog</h2>
<form action="$_SERVER[PHP_SELF]" method="post" id="updateform">
<p>Title:</p><p><input type="text" name="title" value="$row
[title]" class="datafield" /></p>
<p>Author:</p><p><input type="text" name="author" value="$row
[author]" class="datafield" /></p>
<p>Update your content below</p><p><textarea name="content">$row
[content]</textarea></p>
<p><input type="submit" name="updateblog" value="Update
Blog" /></p>
<input type="hidden" value="$id" name="id" />
</form>
</div>
EOD;
            return $output;
            }
} 

As you’ll certainly appreciate, the definition of the new method is closely similar to “displayInsertForm()”, which was covered in the section you just read. This new method simply displays the corresponding update web form where all its boxes has been previously populated with the data that corresponds to the entry being updated (hence the execution of the SELECT statement in the first lines of code).

With reference to the prior method in particular, the only thing worth noticing is the inclusion of a hidden box to store the respective ID of the blog entry being updated. Quite simple, isn’t it?

All right, at this stage you hopefully grasped the logic that stands behind the “BlogProcessor” class, and you understand how it displays the complete list of blogs and shows the pair of web forms necessary for inserting new blogs and updating previous ones. Thus, the next step involved in the development of this extensible blog application rests on creating three additional methods. These will be responsible for displaying programmatically the different sections that compose the main web page of the blogger, that is the header, the primary area and finally the footer.

To learn how these useful methods will be created, be a bit more patient and read the following section. We’re almost finished!

{mospagebreak title=Defining the displayHeader() and displayFooter() methods}

Having provided the “BlogProcessor” class with the ability to display the web forms required for inserting and updating blog entries, the only step that remains still undefined is assembling the different sections that compose the main web page of the blogger in question.

In order to address the issues that I mentioned above, I’m going to define two additional methods. The the first one obviously will take care of generating the header of the main page, while the second one will be aimed at rendering the footer.

Now that you know what tasks will be performed by these two new methods, please have a look at their respective signatures. Here they are:

// display page header
            private function displayHeader(){
$output=<<<EOD
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<title>Blogger System</title>
<link href="styles.css" rel="stylesheet" type="text/css"
media="screen" />
<script language="javascript" src="valfunctions.js"></script>
</head>
<body>
<h1>PHP-BASED BLOG SYSTEM</h1>
EOD;
            return $output;
}
// display page footer
private function displayFooter(){
            return ‘</body></html>';
}

As you can see above, the “displayHeader()” and “displayFooter()” methods are simple wrappers for the respective header and footer sections that comprise the primary web page of the blog application. Also, you should notice that I decided to include a CSS file along with the header, which logically will improve the overall look and feel of the program.

In addition, the “displayHeader()” method includes a JavaScript file called “valfunctions.js” that will take care of performing a basic client-side validation on the data entered in the respective insertion and update web forms. However, both CSS and JavaScript files that I mentioned previously will be shown in the last article of this series, therefore at least for the moment, keep them away of your mind.

Okay, now that you learned the signature for this pair of new methods, I’ll create two new useful ones, in this case called “displayMainPage()” and “displayUpdatePage()” respectively. As their names suggest, they will be tasked with rendering the primary web page of the blogger and the update web document.

That said, here are the corresponding definitions for these private methods:

// display main page
private function displayMainPage(){
            return $this->displayHeader().$this->displayBlogs
().$this->displayInsertForm().$this->displayFooter();
}
// display edit page
private function displayEditPage(){
            return $this->displayHeader().$this-
>displayUpdateForm().$this->displayFooter();
}

Wasn’t that simple? The two additional methods that I just created above are the last ones required to complete the blogger. Of course, I’m quite sure that you want to see the full source code that corresponds to the blog application. Below you can see how the complete “BlogProcessor” class now looks:

class BlogProcessor{
            private $mysql;
            private $blogData;
            public function __construct(MySQL $mysql){
                        $this->mysql=$mysql;
                        $this->blogData=$_POST;
            }
            // display blog system
            public function displayBlogger(){
                        // edit blog
                        if($this->blogData['editblog']){
                                   // display edit page
                                   return $this->displayEditPage();
                        }
                        else{
                                   // insert new blog
                                   if($this->blogData['insertblog']){
                                               $this->insertBlog();
                                   }
                                   // update blog
                                   elseif($this->blogData['updateblog']){
                                               $this->updateBlog();
                                   }
                                   // delete blog
                                   elseif($this->blogData['deleteblog']){
                                               $this->deleteBlog();       
                                   }
                        }
                        // display main page
                        return $this->displayMainPage();
            }
            // insert new blog
            private function insertBlog(){
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("INSERT INTO blogs
(id,author,title,content,date) VALUES (NULL,’$author’,’$title’,’$content’,TIMESTAMP
(10))");
                        header(‘Location:’.$_SERVER['PHP_SELF']);                             
            }
            // update blog
            private function updateBlog(){
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("UPDATE blogs SET
title=’$title’,author=’$author’,content=’$content’,date=TIMESTAMP(10) WHERE
id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);
            }
            // delete blog
            private function deleteBlog(){
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("DELETE FROM blogs WHERE id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);
            }
            // display all the blogs
            private function displayBlogs(){
                        $result=$this->mysql->query("SELECT * FROM blogs");
                        $output=”;
                        while($row=$result->fetchRow()){
                                   $content=nl2br($row['content']); 
$output.=<<<EOD
<div class="blog">
<h2>$row[title]</h2>
<h3> Author: $row[author]<h3>
<h3> Posted: $row[date]</h3>
<p>$content</p>
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="submit" value="Edit Blog" name="editblog" />
<input type="submit" value="Delete Blog" name="deleteblog" />
<input type="hidden" value="$row[id]" name="id" />
</form>
</div>
EOD;
                        }
                        return $output;
            }
            // display insertion form
            private function displayInsertForm(){
$output=<<<EOD
<div class="dataform">
<h2>Insert New Blog</h2>
<form action="$_SERVER[PHP_SELF]" method="post" id="insertform">
<p>Title:</p><p><input type="text" name="title" class="datafield" /></p>
<p>Author:</p><p><input type="text" name="author" class="datafield" /></p>
<p>Type your content below</p><p><textarea
name="content"></textarea></p>
<p><input type="submit" name="insertblog" value="Insert Blog" /></p>
</form>
</div>
EOD;
                        return $output;   
            }
            // display update form
            private function displayUpdateForm(){
                        $id=$this->blogData['id'];
                        $result=$this->mysql->query("SELECT * FROM blogs WHERE
id=’$id’");
                        if($result->countRows()>0){
                                   $row=$result->fetchRow();
$output=<<<EOD
<div class="dataform">
<h2>Update Blog</h2>
<form action="$_SERVER[PHP_SELF]" method="post" id="updateform">
<p>Title:</p><p><input type="text" name="title" value="$row[title]"
class="datafield" /></p>
<p>Author:</p><p><input type="text" name="author" value="$row[author]"
class="datafield" /></p>
<p>Update your content below</p><p><textarea name="content">$row[content]</textarea></p>
<p><input type="submit" name="updateblog" value="Update Blog" /></p>
<input type="hidden" value="$id" name="id" />
</form>
</div>
EOD;
                                   return $output;
                        }
            }
            // display page header
            private function displayHeader(){
$output=<<<EOD
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Blogger System</title>
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
<script language="javascript" src="valfunctions.js"></script>
</head>
<body>
<h1>PHP-BASED BLOG SYSTEM</h1>
EOD;
                        return $output;
            }
            // display page footer
            private function displayFooter(){
                        return ‘</body></html>';
            }
            // display main page
            private function displayMainPage(){
                        return $this->displayHeader().$this->displayBlogs().$this-
>displayInsertForm().$this->displayFooter();
            }
            // display edit page
            private function displayEditPage(){
                        return $this->displayHeader().$this->displayUpdateForm().$this-
>displayFooter();
            }
}

Now, after seeing the full source code of the blog application, you’ll agree with me that every piece of code makes much more sense. As I say in every article, feel free to tweak the code of each method shown here and introduce your own modifications. It’s really fun!

Wrapping up

In this second part of the series, I defined all remaining methods that belong to the blog processor, in order to turn it into an almost fully-functional class. Why did I say “almost”? Well, there’s still a couple of things that need to be done, such as defining the MySQL wrapping class aggregated by the blog processor, in addition to defining the CSS and JavaScript files that I mentioned a few lines before.

However, as you’ll probably imagine, all these issues will be covered in the last part, so you don’t have any excuses to miss it!

[gp-comments width="770" linklove="off" ]

chat