10.7. Deleting Comments

Your last step is to provide site administrators with the ability to remove comments from entries. You've already created the link to delete comments; now you need to tell your application what to do when the link is clicked.

The link you've built directs you to update.inc.php. It also passes two values using the GET method: an action, set to comment_delete; and an id, set to the value of the comment you created the link for.

To avoid accidental comment deletion, you can use a two-step process to delete comments. After clicking the link, the user receives a confirmation form generated by the confirmDelete() method (which you'll write in a moment). The form asks the user to confirm his decision to delete the comment. If he clicks "Yes,", you call the yet-to-be-written deleteComment() method, which removes the comment from the database.

10.7.1. Creating a Confirmation Form

When building the confirmation form, begin by writing a method in the Comments class that displays a confirmation form to a user when a delete link is clicked. This method, named confirmDelete(), accepts one argument: the ID of the comment the user wants to delete ($id). When this method is called:, your first step is to attempt to retrieve the URL of the user's entry form. You want to have this available so you can send the user back to the entry she was viewing when she clicked the delete link. You can do this by checking whether the value of $_SERVER['HTTP_REFERER'] has been set, then storing that value in a variable called $url (again, assuming the value has been set). If it hasn't been set, you use the "../" value to send the user to the default entry preview page.

After you store the URL of the previous entry in $url, use the heredoc syntax to construct an HTML form using the $id and $url variables; this form asks the user if she really wants to delete the comment. You provide the user with "Yes" and "No" buttons to answer.

Do this by adding the confirmDelete() method to the Comments class in comments.inc.php:

// Ensure the user really wants to delete the comment
    public function confirmDelete($id)
    {
        // Store the entry url if available
        if(isset($_SERVER['HTTP_REFERER']))
        {
            $url = $_SERVER['HTTP_REFERER'];
        }

        // Otherwise use the default view
        else
        {
            $url = '../';
        }

        return <<<FORM
<html>
<head>
<title>Please Confirm Your Decision</title>
<link rel="stylesheet" type="text/css"
    href="/simple_blog/css/default.css" />
</head>
<body>
<form action="/simple_blog/inc/update.inc.php" method="post">
    <fieldset>
        <legend>Are You Sure?</legend>
        <p>
            Are you sure you want to delete this comment?
        </p>

<input type="hidden" name="id" value="$id" />
        <input type="hidden" name="action" value="comment_delete" />
        <input type="hidden" name="url" value="$url" />
        <input type="submit" name="confirm" value="Yes" />
        <input type="submit" name="confirm" value="No" />
    </fieldset>
</form>
</body>
</html>
FORM;
    }

NOTE

You build this form with a page title and a link to your stylesheet because update.inc.php outputs this form directly, which means that no output is generated before or after the markup returned by this function. For this reason, you need to create a full HTML page with this method; this enables you to keep your form consistent with the styling of your blog.

10.7.2. Removing the Comment from the Database

Your next step is to create the method that removes a comment from the database. This method, which you call deleteComment(), accepts one argument: the ID of the comment you want to delete ($id).

This method is simple: you construct a SQL query, prepare it, and execute it using the value of $id. If no errors occur, you return TRUE; otherwise, you return FALSE.

Add this code to the Comments class in comments.inc.php to create the deleteComment() method:

// Removes the comment corresponding to $id from the database
    public function deleteComment($id)
    {
        $sql = "DELETE FROM comments
                WHERE id=?
                LIMIT 1";
        if($stmt = $this->db->prepare($sql))
        {
            // Execute the command, free used memory, and return true
            $stmt->execute(array($id));
            $stmt->closeCursor();
            return TRUE;
        }

else
        {
            // If something went wrong, return false
            return FALSE;
        }
    }

10.7.3. Modifying update.inc.php to Handle Comment Deletion

You now have methods in place to confirm that a comment is to be deleted and to remove that comment from the database. This means you're ready to modify update.inc.php to handle the comment's deletion.

Begin by adding an else if block to update.inc.php. This block of code checks whether the $_GET superglobal contains an index called "action" that you set to comment_delete. If so, you load and instantiate the Comments class and output the return value of confirmDelete().

Add the code in bold to the bottom of update.inc.php, just before the last else block:

// If the delete link is clicked on a comment, confirm it here
else if($_GET['action'] == 'comment_delete')
{
    // Include and instantiate the Comments class
    include_once 'comments.inc.php';
    $comments = new Comments();
    echo $comments->confirmDelete($_GET['id']);
    exit;
}

else
{
    header('Location: ../'),
    exit;
}

?>

To see the confirmation form, navigate to the blog entry with your test comment and click the delete link just below the test comment. This takes you to your confirmation form (see Figure 10-5).

Figure 10.5. Your form that confirms comment deletion

Next, you need to add another elseif block to update.inc.php that checks whether the comment deletion form was submitted via the POST method. You can make sure the confirmation form was submitted by checking whether the $_POST superglobal contains an index called action with a value of comment_delete,.

You need to store the URL you passed via your form in the $_POST['url'] variable. Just to be safe, you check whether the variable was set and provide a default value it wasn't, which you store in the variable $url.

Next, you check whether the "Yes" button was clicked. If so, you include and instantiate the Comments class, then pass the comment ID stored in $_POST['id'] to the deleteComment() method. If the method returns TRUE, you send the user to the URL stored in $url.

If the user clicked No, you send her to the URL stored in $url, doing nothing with the comment.

To implement this, you add the code in bold to the bottom of update.inc.php, just above the last else block:

// If the delete link is clicked on a comment, confirm it here
else if($_GET['action'] == 'comment_delete')
{
    // Include and instantiate the Comments class
    include_once 'comments.inc.php';
    $comments = new Comments();
    echo $comments->confirmDelete($_GET['id']);
    exit;
}

// If the confirmDelete() form was submitted, handle it here
else if($_SERVER['REQUEST_METHOD'] == 'POST'
    && $_POST['action'] == 'comment_delete')

{
    // If set, store the entry from which we came
    $loc = isset($_POST['url']) ? $_POST['url'] : '../';

    // If the user clicked "Yes", continue with deletion
    if($_POST['confirm'] == "Yes")
    {
        // Include and instantiate the Comments class
        include_once 'comments.inc.php';
        $comments = new Comments();

        // Delete the comment and return to the entry
        if($comments->deleteComment($_POST['id']))
        {
            header('Location: '.$loc);
            exit;
        }

        // If deleting fails, output an error message
        else
        {
            exit('Could not delete the comment.'),
        }
    }

    // If the user clicked "No", do nothing and return to the entry
    else
    {
        header('Location: '.$loc);
        exit;
    }
}

else
{
    header('Location: ../'),
    exit;
}

?>

At this point, you can delete comments from the database, thus removing them from your entry display. You can test this out by deleting your test comment. Navigate to the entry that you we entered for the comment in a browser, then click the delete link. Next, click Yes to confirm that you want to delete the comment. This takes you back to the entry, but the comment is no longer there. Instead, you see the default message: "There are no comments for this entry" (see Figure 10-6).

Figure 10.6. After deleting your test comment, you see this default message

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

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