10.6. Displaying Comments for a Given Entry

With retrieveComments() functional, you can now display the entries loaded when a user views an entry on the blog.

You can do this by creating a new showComments() method that accepts the blog ID as an argument ($blog_id). This method begins by initializing an empty variable ($display) to contain the formatted comments, then calls the retrieveComments() method to get the entry's comments loaded into memory.

With the comments loaded into $display, you can loop through each comment and create HTML markup to display them. Inside the loop, you want to check whether retrieveComments() has returned the default value, which means no comments exist for the entry. To do this, you set up a conditional statement that verifies that both the date and name values aren't empty before you create a byline.

Begin by setting up the method, loading the entry comments, and starting the loop. Next, add the showComments() method to comments.inc.php by adding the code in bold to the Comments class:

// Generates HTML markup for displaying comments
    public function showComments($blog_id)
    {
        // Initialize the variable in case no comments exist
        $display = NULL;

        // Load the comments for the entry
        $this->retrieveComments($blog_id);

        // Loop through the stored comments
        foreach($this->comments as $c)
        {
            // Prevent empty fields if no comments exist
            if(!empty($c['date']) && !empty($c['name']))
            {
                // Generate a byline and delete link for each comment
            }
            else
            {
                // If we get here, no comments exist
            }

            // Assemble the pieces into a formatted comment
        }

        // Return all the formatted comments as a string
    }

Your next step is to create a byline for each comment, as well as an administrative link that lets you delete unwanted comments. You accomplish this with an if-else statement.

You need to format a byline if the date and name values aren't empty. You want this byline to display the name of the commenter, as well as the date and time the comment was posted. The format looks like this:

John Doe    [Posted on July 10, 2009 at 6:54PM]

Think back to how you handled dates in previous chapter. You take a similar approach here, changing the format of the MySQL timestamp stored in the database to fit your needs. You use the strtotime() and date() methods again, but this time you need to create a custom date formatting string.

FORMATTING DATES IN PHP USING THE DATE() FUNCTION

PHP provides you with many options for formatting dates when you use the date() function. You can format each part of a date (day, month, year, and so on) using one of several available formatting characters, which you can combine as necessary to create custom dates.

For example, you would use the formatting string "M d, Y" to create the date format, "Jan 01, 2009". Any character used that is not a formatting character—like the comman in the previous example—is output as-is.

If you wish to output text that features a formatting character, you must escape it using a backslash (). For example, this format "m/d/y a\t g:IA" outputs a date similar to "01/01/09 at 4:10PM".

Commonly Used Formatting Characters Recognized by the Date() Function

Format CharacterDescriptionExample Return Value
Day  
dDay of the month, two digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
lFull textual representation of the day of the weekSunday through Saturday
SEnglish ordinal suffix for the day of the monthst, nd, rd or th; this works well with j
Month  
FA full textual representation of a monthJanuary through December
mNumeric representation with leading zeros01 through 12
MA short textual representation of a monthJan through Dec
nNumeric representation without leading zeros1 through 12
tNumber of days in the given month28 through 31
Year  
YA full numeric representation of a year, four digitsExamples: 1999 or 2003
yA two digit representation of a yearExamples: 99 or 03
Time  
aLowercase ante meridiem and post meridiemam or pm
AUppercase ante meridiem and post meridiemAM or PM
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
IMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 through 59
Time zone  
TTime zone abbreviationExamples: EST, MDT, and so on

Note that this table doesn't list all of the available formatting characters. For a full reference of such characters, look up the date() entry in the PHP manual at http://php.net/date.


You store your formatting string in a variable called $format, which makes it easy to identify and change in the future, if necessary. Use this formatting string for your comment byline: F j, Y a\t g:iA.

NOTE

In the "F j, Y a\t g:iA" formatting string, the "t" is escaped twice. You need to do it this way because is a whitespace character in PHP, which means that it would result in unexpected output if you don't double-escape it. The same goes for other whitespace characters, including and .

With our format stored, you're ready to convert the MySQL timestamp to a Unix timestamp using strtotime(), then use date() to produce the desired date format, which you store in a variable called $date.

Next, place the commenter's name and the formatted date into HTML tags to create the desired output; store this output in a variable called $byline.

Finally, you create the markup for a link to delete the comment, which you store in a variable called $admin.

In the else block, which you get to only if no comments exist for the blog entry, you set $byline and $admin to NULL because they are unnecessary if no comments exist.

Add the code in bold to showComments() in comments.inc.php:

// Generates HTML markup for displaying comments
    public function showComments($blog_id)
    {
        // Initialize the variable in case no comments exist
        $display = NULL;

        // Load the comments for the entry
        $this->retrieveComments($blog_id);

        // Loop through the stored comments
        foreach($this->comments as $c)
        {
            // Prevent empty fields if no comments exist
            if(!empty($c['date']) && !empty($c['name']))
            {
                // Outputs similar to: July 8, 2009 at 4:39PM
                $format = "F j, Y a\t g:iA";

                // Convert $c['date'] to a timestamp, then format
                $date = date($format, strtotime($c['date']));

                // Generate a byline for the comment
                $byline = "<span><strong>$c[name]</strong>
                            [Posted on $date]</span>";

                // Generate delete link for the comment display
                $admin = "<a href="/simple_blog/inc/update.inc.php"
                    . "?action=comment_delete&id=$c[id]""
                    . "class="admin">delete</a>";
            }
            else

{
                // If no comments exist, set $byline & $admin to NULL
                $byline = NULL;
                $admin = NULL;
            }

            // Assemble the pieces into a formatted comment
        }

        // Return all the formatted comments as a string
    }

NOTE

You'll learn about the delete link and how it works in the "Deleting Comments" section.

You've stored your byline and administrative links; now place them into HTML markup with the comment itself. You append each comment to the $display variable, which is returned from the function after the loop is finished.

To finish the showComments()method, add the code in bold to your method in comments.inc.php:

// Generates HTML markup for displaying comments
    public function showComments($blog_id)
    {
        // Initialize the variable in case no comments exist
        $display = NULL;

        // Load the comments for the entry
        $this->retrieveComments($blog_id);

        // Loop through the stored comments
        foreach($this->comments as $c)
        {
            // Prevent empty fields if no comments exist
            if(!empty($c['date']) && !empty($c['name']))
            {
                // Outputs similar to: July 8, 2009 at 4:39PM
                $format = "F j, Y a\t g:iA";

                // Convert $c['date'] to a timestamp, then format
                $date = date($format, strtotime($c['date']));

// Generate a byline for the comment
                $byline = "<span><strong>$c[name]</strong>
                            [Posted on $date]</span>";

                // Generate delete link for the comment display
                $admin = "<a href="/simple_blog/inc/update.inc.php
?action=comment_delete&id=$c[id]" class="admin">delete</a>";
            }
            else
            {
                // If no comments exist, set $byline & $admin to NULL
                $byline = NULL;
                $admin = NULL;
            }

            // Assemble the pieces into a formatted comment
            $display .= "
<p class="comment">$byline$c[comment]$admin</p>";
        }

        // Return all the formatted comments as a string
        return $display;
    }

10.6.1. Modifying index.php to Display Entry Comments

You have your methods for loading and formatting comments in place. Now you're ready to open index.php and insert the comment display into your blog entries.

You've already done most of the work necessary by adding the comment form. All that remains is to create new variable called $comment_disp and store the output of showComments(). Place this new variable (in bold) just before the value of $comment_form in the index.php file, starting at line 83:

// If the full display flag is set, show the entry
if($fulldisp==1)
{

    // Get the URL if one wasn't passed
    $url = (isset($url)) ? $url : $e['url'];

    // Build the admin links
    $admin = adminLinks($page, $url);

    // Format the image if one exists
    $img = formatImage($e['image'], $e['title']);

if($page=='blog')
    {
        // Load the comment object
        include_once 'inc/comments.inc.php';
        $comments = new Comments();
        $comment_disp = $comments->showComments($e['id']);
        $comment_form = $comments->showCommentForm($e['id']);
    }
    else
    {
        $comment_form = NULL;
    }

?>

        <h2> <?php echo $e['title'] ?> </h2>
        <p> <?php echo $img, $e['entry'] ?> </p>
        <p>
            <?php echo $admin['edit'] ?>
            <?php if($page=='blog') echo $admin['delete'] ?>
        </p>
        <?php if($page=='blog'): ?>
        <p class="backlink">
            <a href="./">Back to Latest Entries</a>
        </p>
        <h3> Comments for This Entry </h3>
        <?php echo $comment_disp, $comment_form; endif; ?>

<?php

} // End the if statement

Once you save the file, you can navigate to the blog entry you've created a test comment for, and you should see the comment displayed with a byline and an administrative link in place (see Figure 10-4).

Figure 10.4. Comments displayed for an entry

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset