Part 9: Creating a form to edit and delete comments

Originally posted by Julie.

Please note: The Build-A-Blog series is an introduction to creating a simple blog script using PHP. These tutorials are meant to help you to learn PHP and MySQL and to use these to fetch and store data and display it on a web page. These tutorials should not be used ‘as is’ on a production website – especially if you are new to PHP and do not understand what you are doing. We would recommend that you try the B-A-B series on a safe, development environment – such as an offline installation of PHP and MySQL – so you can learn how everything works.

GWG and its staffers accept no responsibility for anything that may (or may not) happen to your site or server as a result of you using these tutorials – you do so AT YOUR OWN RISK.

As you may or may not know, Michelle is currently unable to add to the Build A Blog series of tutorials, so I thought I’d try my hand at writing a new instalment. I can’t promise it will be as good as her tutorials, but I’ll do my best! This tutorial covers the creation of an admin page for editing and deleting user comments.

This code is based on Michelle’s tutorial for creating a form to edit entries. I’ve also followed her style of coding to keep this tutorial similar to the previous ones.

Before following this tutorial, you need to set up comments by following Part 7: Allowing Reader Comments.

Let’s start by creating a page called editcomments.php. This page needs to go in the same password protected directory as your blog entry and edit pages to keep it secure.

First, open PHP:

<?php

Connect to your database (change the values as applicable):

mysql_connect ('localhost', 'db_username', 'db_password') ;
mysql_select_db ('db_name');

Now, we will write an if statement to check if the edit form (which we’ll create further down the page) has been submitted, and if so, to process it by updating the database with the new posted info. Here we will also strip out HTML as a security measure:

if (isset($_POST['edit'])) {
    $name = htmlspecialchars(strip_tags($_POST['name']));
    $email = htmlspecialchars(strip_tags($_POST['email']));
    $url = htmlspecialchars(strip_tags($_POST['url']));
    $comment = htmlspecialchars(strip_tags($_POST['comment']));
    $comment = nl2br($comment);
    $id = (int)$_POST['id'];

    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
        $url = addslashes($url);
        $comment = addslashes($comment);
    }

    $result = mysql_query("UPDATE php_blog_comments SET name='$name', email='$email', url='$url', comment='$comment' WHERE id='$id' LIMIT 1") or print ("Can't update comment.<br />" . $result . "<br />" . mysql_error());
    if ($result != false) {
        print "<p>The comment has successfully been edited!</p>";
    }
}

Next, another if statement to check if the delete form (again, we’ll create it further down the page) has been submitted, and if so, to process it by deleting the comment from the database and posting a success message:

if(isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    $result = mysql_query("DELETE FROM php_blog_comments WHERE id='$id' LIMIT 1") or print ("Can't delete comment.<br />" . $result . "<br />" . mysql_error());
    if ($result != false) {
        print "<p>The comment has successfully been deleted!</p>";
    }
}

Just like the edit entries page, the form to edit a comment only shows up if the url is http://yourdomain.com/dir/editcomments.php?id=xx where xx is the id number of the comment. So, now we will write an if statement to check if that variable $id has been passed through the URL, and whether it’s a valid ID (i.e. it’s not zero or a letter):

if (isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id'])) {

Take note that it’s necessary here to use $_GET[‘id’] instead of just $id, even if you have register_globals on. $_GET holds the variables passed through the URL and not those from forms, cookies, or other methods. For this particular statement, we only want to check for a query string (URL) variable here, so it’s important to make the distinction.

So, if $_GET[‘id’] is set, that means we can show the edit form for the comment with that id number. First we select the comment from the database:

$result = mysql_query ("SELECT * FROM php_blog_comments WHERE id='$_GET[id]'") or print ("Can't select comment.<br />" . mysql_error());

Then use a while loop to set variables for the existing comment data:

while ($row = mysql_fetch_array($result)) {
      $old_name = stripslashes($row['name']);
      $old_email = $row['email'];
      $old_url = stripslashes($row['url']);
      $old_comment = stripslashes($row['comment']);
      $old_comment = str_replace('<br />', '', $old_comment);
}

And now the form, which we will fill with the values we just set. Note that there are three submit buttons: one to save changes, one to delete the comment, and one to cancel with no changes made (it just takes you back to the edit comments menu, which we’ll create further down in the tutorial). Here we close PHP for a bit so that we can add some normal HTML, but we will reopen it as and when needed.:

?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <p><input type="hidden" name="id" id="id" value="<?php echo $_GET['id']; ?>">

    <strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="40" value="<?php echo $old_name; ?>" /></p>

    <p><strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="40" value="<?php echo $old_email; ?>" /></p>

    <p><strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="40" value="<?php echo $old_url; ?>" /></p>

    <p><strong><label for="comment">Comment:<label></strong><br />
    <textarea cols="80" rows="20" name="comment" id="comment"><?php echo $old_comment; ?></textarea></p>

    <p><input type="submit" name="edit" id="edit" value="Save Changes"> <input type="submit" name="delete" id="delete" value="Delete Comment"> <input type="submit" value="Never Mind"></p>

</form>
<?php

Now for the else that goes with the if $_GET[‘id’] above. So everything below this is now if $_GET[‘id’] is not set:

}
else {

What we are creating now is the edit comments menu that shows up by default if you just go to editcomments.php with no ?id=xx. It involves three database queries – the second and third being nested inside the first. The first query selects from the comments table the id of each blog entry that has comments. The second query then gets the date and title of the entry from the blog table. The third query gets the comments from that entry. Here it goes…

The first query. The limit is set to 10 entries worth of comments to keep the page from being too long, but you can change it to whatever number you like, or just remove the limit completely:

$result = mysql_query("SELECT entry AS get_group FROM php_blog_comments GROUP BY get_group DESC LIMIT 10") or print ("Can't select comments.<br />" . $result . "<br />" . mysql_error());

Now start the while loop and set the value of $get_group, which in this case is the id number of an entry. Then open a paragraph to hold each entry’s comment links (to keep things neat). We don’t close the while loop yet because the next two are nested inside this one… we’ll close it later on:

while($row = mysql_fetch_array($result)) {
     $get_group = $row['get_group'];

     print "<p>";

The second query, to get the timestamp and title from the blog table. Inside the while loop, we format the date and then print the date and title. This while loop can be closed here, because the third query doesn’t depend on it.

    $result2 = mysql_query("SELECT timestamp, title FROM php_blog WHERE id='$get_group'");
    while($row2 = mysql_fetch_array($result2)) {
        $date = date("l F d Y",$row2['timestamp']);
        $title = stripslashes($row2['title']);
        print "<strong>" . $date . " - " . $title . "</strong><br />";
    }

Now the final query to get the comment info so we can format it to be linked to the edit page. Don’t close this while loop just yet, there’s more:

    $result3 = mysql_query("SELECT * FROM php_blog_comments WHERE entry='$get_group' ORDER BY timestamp DESC");
    while($row3 = mysql_fetch_array($result3)) {
        $id = $row3['id'];
        $name = stripslashes($row3['name']);
        $comment = stripslashes($row3['comment']);
        $date = date("l F d Y",$row3['timestamp']);

We want to know which comment we are clicking on to edit, but if we displayed each comment in full, the page could get quite lengthy. So, we can check to see if the comment is longer than 75 characters, and if it is, trim it and put an ellipsis on the end. We’re also stripping line breaks in order to keep the size down as well:

        if (strlen($comment) > 75 || strstr($comment, "<br />") || strstr($comment, "\n")) {
            $comment = substr($comment,0,75) . "...";
            $comment = str_replace("<br />", "", $comment);
            $comment = str_replace("\n", " ", $comment);
        }

Now print the comment (or comment snippet), linked to the edit form for that comment:

        print "<a href=\"editcomments.php?id=" . $id . "\">" . $comment . "</a><br />Comment by " . $name . " @ " . $date;

Close the paragraph, the third query’s while loop, the first query’s while loop and then the else part we opened earlier:

        print "</p>";

    }
}
}

Then close the database connection:

mysql_close();

And finally, close PHP:

?>

Here’s the whole code for the editcomments.php page:

<?php
mysql_connect ('localhost', 'db_username', 'db_password') ;
mysql_select_db ('db_name');

if (isset($_POST['edit'])) {
    $name = htmlspecialchars(strip_tags($_POST['name']));
    $email = htmlspecialchars(strip_tags($_POST['email']));
    $url = htmlspecialchars(strip_tags($_POST['url']));
    $comment = htmlspecialchars(strip_tags($_POST['comment']));
    $comment = nl2br($comment);
    $id = (int)$_POST['id'];

    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
        $url = addslashes($url);
        $comment = addslashes($comment);
    }

    $result = mysql_query("UPDATE php_blog_comments SET name='$name', email='$email', url='$url', comment='$comment' WHERE id='$id' LIMIT 1") or print ("Can't update comment.<br />" . $result . "<br />" . mysql_error());
    if ($result != false) {
        print "<p>The comment has successfully been edited!</p>";
    }
}

if(isset($_POST['delete'])) {
$id = (int)$_POST['id'];
     $result = mysql_query("DELETE FROM php_blog_comments WHERE id='$id' LIMIT 1") or print ("Can't delete comment.<br />" . $result . "<br />" . mysql_error());
     if ($result != false) {
         print "<p>The comment has successfully been deleted!</p>";
     }
}

if (isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id'])) {

$result = mysql_query ("SELECT * FROM php_blog_comments WHERE id='$_GET[id]'") or print ("Can't select comment.<br />" . mysql_error());

while ($row = mysql_fetch_array($result)) {
      $old_name = stripslashes($row['name']);
      $old_email = $row['email'];
      $old_url = stripslashes($row['url']);
      $old_comment = stripslashes($row['comment']);
      $old_comment = str_replace('<br />', '', $old_comment);
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <p><input type="hidden" name="id" id="id" value="<?php echo $_GET['id']; ?>">

    <strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="40" value="<?php echo $old_name; ?>" /></p>

    <p><strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="40" value="<?php echo $old_email; ?>" /></p>

    <p><strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="40" value="<?php echo $old_url; ?>" /></p>

    <p><strong><label for="comment">Comment:<label></strong><br />
    <textarea cols="80" rows="20" name="comment" id="comment"><?php echo $old_comment; ?></textarea></p>

    <p><input type="submit" name="edit" id="edit" value="Save Changes"> <input type="submit" name="delete" id="delete" value="Delete Comment"> <input type="submit" value="Never Mind"></p>

</form>
<?php

}
else {

$result = mysql_query("SELECT entry AS get_group FROM php_blog_comments GROUP BY get_group DESC LIMIT 10") or print ("Can't select comments.<br />" . $result . "<br />" . mysql_error());

while($row = mysql_fetch_array($result)) {
     $get_group = $row['get_group'];

     print "<p>";

    $result2 = mysql_query("SELECT timestamp, title FROM php_blog WHERE id='$get_group'");
    while($row2 = mysql_fetch_array($result2)) {
        $date = date("l F d Y",$row2['timestamp']);
        $title = stripslashes($row2['title']);
        print "<strong>" . $date . " - " . $title . "</strong><br />";
    }

    $result3 = mysql_query("SELECT * FROM php_blog_comments WHERE entry='$get_group' ORDER BY timestamp DESC");
    while($row3 = mysql_fetch_array($result3)) {
        $id = $row3['id'];
        $name = stripslashes($row3['name']);
        $comment = stripslashes($row3['comment']);
        $date = date("l F d Y",$row3['timestamp']);

        if (strlen($comment) > 75 || strstr($comment, "<br />") || strstr($comment, "\n")) {
            $comment = substr($comment,0,75) . "...";
            $comment = str_replace("<br />", "", $comment);
            $comment = str_replace("\n", " ", $comment);
        }

        print "<a href=\"editcomments.php?id=" . $id . "\">" . $comment . "</a><br />Comment by " . $name . " @ " . $date;
        print "</p>";

    }
}
}
mysql_close();

?>

That’s it! Remember to insert your database connection info and to change the table names if yours aren’t php_blog and php_blog_comments. You should now have an admin panel to edit and delete comments. If you have any problems, please post in the tutorials forum!