Part 7: Allowing reader comments

Originally posted by Michelle.

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.

Now we’re ready to set up commenting for our blogs. I know you’ve all been waiting for this, and now you can stop sending me death threats. ;)

There are three basic steps to getting our comments up and running:

  1. Create a table for the comments
  2. Create a form for entering comments
  3. Show comments on individual entries

First we’ll write an install.php file to create our comments table. Open PHP:

<?php

Connect to the database (change the values to your own!):

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

Here’s the SQL query. We’re creating a table called phpblogcomments, with columns called id, entry (which will be the id of the journal entry the comment belongs to), name, email, url, comment, and timestamp. Id is the primary key and the unique key. You should be familiar with this from creating the initial database:

$sql = "CREATE TABLE php_blog_comments (
  id int(20) NOT NULL auto_increment,
  entry int(20) NOT NULL,
  name varchar(255) NOT NULL,
  email varchar(255) NOT NULL,
  url varchar(255) NOT NULL,
  comment longtext NOT NULL,
  timestamp int(20) NOT NULL,
  PRIMARY KEY  (id)
)";

Now execute the sql query, or print an error message:

$result = mysql_query($sql) or print("Can't create the table 'php_blog_comments' in the database.<br />" . $sql . "<br />" . mysql_error());

And a success message if it works:

if ($result != false) {
    echo "Table 'php_blog_comments' was successfully created.";
}

Close mysql:

mysql_close();

Close php:

?>

Here’s the whole thing:

<?php

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

$sql = "CREATE TABLE php_blog_comments (
  id int(20) NOT NULL auto_increment,
  entry int(20) NOT NULL,
  name varchar(255) NOT NULL,
  email varchar(255) NOT NULL,
  url varchar(255) NOT NULL,
  comment longtext NOT NULL,
  timestamp int(20) NOT NULL,
  PRIMARY KEY  (id)
)";

$result = mysql_query($sql) or print("Can't create the table 'php_blog_comments' in the database.<br />" . $sql . "<br />" . mysql_error());

if ($result != false) {
    echo "Table 'php_blog_comments' was successfully created.";
}

mysql_close();

?>

Upload this file and point your browser to it. Once the table is created, delete the file for security.

Now, let’s write the form to accept comments. Open up your individual entry page. This is going to go right after the while loop that prints your entries, which currently looks like this (this is the version WITH password protection. If you haven’t enabled password protection in your blog, your code will look slightly different):

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>

                 <p><strong><?php echo $title; ?></strong><br /><br />

                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?></p>

                <?php
             }
             else { ?>
                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?></p>

        <?php
    }
}

Directly below this loop (but before the closing ?> in your complete code), add the following line:

$commenttimestamp = strtotime("now");

Here we’re grabbing the current timestamp for comments.

All the following code (the HTML form) should be placed below the closing ?> in your code.

Open your form:

<form method="post" action="process.php">

Process.php should be whatever file you plan to use to process the comment. You can do this in the same file, but you end up with a MySQL error for a split second while it inserts. This is because for just a moment you’re looking at filename.php instead of the proper filename.php?id=xx

We’re going to need a couple of hidden fields. One inserts the id of the entry we’re looking at, and the other the timestamp:

<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />

<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">

Now your regular input fields, name, email, url and comment:

<strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="25" /><br />

<strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="25" /><br />

<strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="25" value="http://" /><br />

<strong><label for="comment">Comment:</label></strong><br />
<textarea cols="25" rows="5" name="comment" id="comment"></textarea></p>

And the submit button, which we’re calling submit_comment:

<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>

Close your form:

</form>

Now, this is a very basic form, you might want to put yours in a box or something to make it look nice on your site. I’ll leave that up to you.

Your whole individual entry page should now look something like this (depending on whether you’ve got password protection enabled – again, this is the version WITH password protection):

<?php

$my_username = "USERNAME";
$my_password = "PASSWORD";

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid ID specified.");
}

$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";

$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>

                 <p><strong><?php echo $title; ?></strong><br /><br />
                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?></p>

                <?php
             }
             else { ?>
                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?></p>

        <?php
    }
}
$commenttimestamp = strtotime("now");
?>

<form method="post" action="process.php">

<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />

<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">

<strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="25" /><br />

<strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="25" /><br />

<strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="25" value="http://" /><br />

<strong><label for="comment">Comment:</label></strong><br />
<textarea cols="25" rows="5" name="comment" id="comment"></textarea></p>

<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>

</form>

Let’s create process.php, which will process your comments. Make sure that you do not lump this in with the file that processes your blog entries, and don’t name it the same if they are in the same directory. In fact, your blog processing page should be in a secure directory to keep random people from messing with your blog.

First, open php:

<?php

Now, if we’ve pressed to submit a comment…

if (isset($_POST['submit_comment'])) {

}

Let’s check they submitted all the required information. Here I’m requiring a name, a valid e-mail address and a comment.

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

}

Let’s then have it strip tags from our input as a security feature:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $name = htmlspecialchars(strip_tags($_POST['name']));
    $email = htmlspecialchars(strip_tags($_POST['email']));
    $url = htmlspecialchars(strip_tags($_POST['url']));
    $comment = htmlspecialchars(strip_tags($_POST['comment']));
}

And have it save linebreaks in the comments:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);
}

Next we need to escape quotes in our data if the server doesn’t do it for us:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

Now let’s validate that e-mail address and see if it’s a real one:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }
}

Now tell it to connect to our database (replace the database information with your own):

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }

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

And insert the comment:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }

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

    $result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");
}

Now let’s have it forward us back to the entry we’re commenting on:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }

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

    $result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");

    header("Location: journal.php?id=" . $entry);
}

Then we’ll add a little snippet to stop people from coming directly to our process page:

if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }

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

    $result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");

    header("Location: journal.php?id=" . $entry);
}
else {
    die("Error: you cannot access this page directly.");
}

Close php:

?>

And this is how the process.php should look:

<?php
if (isset($_POST['submit_comment'])) {

    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comment'])) {
        die("You have forgotten to fill in one of the required fields! Please make sure you submit a name, e-mail address and comment.");
    }

    $entry = htmlspecialchars(strip_tags($_POST['entry']));
    $timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
    $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);

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

    if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
         die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
    }

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

    $result = mysql_query("INSERT INTO php_blog_comments (entry, timestamp, name, email, url, comment) VALUES ('$entry','$timestamp','$name','$email','$url','$comment')");

    header("Location: journal.php?id=" . $entry);
}
else {
    die("Error: you cannot access this page directly.");
}
?>

Finally we need to show comments on individual entries. Open your individual entry page again. Add this right after the comment timestamp line, but BEFORE the comment form, and AFTER the closing ?> :.

First an SQL query to select the comments that go with the current blog entry:

$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";

Execute the query or print an error:

$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());

While this is true, convert the timestamp, and print the entry:

while($row = mysql_fetch_array($result)) {
    $timestamp = date("l F d Y", $row['timestamp']);
    printf("<hr />");
    print("<p>" . stripslashes($row['comment']) . "</p>");
    printf("<p>Comment by <a href=\"%s\">%s</a> @ %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
    printf("<hr />");
}

I only put horizontal rules around the comments, you may want to make them prettier.

Now your whole individual entry page should look like this (remember that this is the password protected version – yours may look slightly different if you haven’t enabled password protection!):

<?php

$my_username = "USERNAME";
$my_password = "PASSWORD";

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid ID specified.");
}

$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";

$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>

                 <p><strong><?php echo $title; ?></strong><br /><br />
                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?></p>

                <?php
             }
             else { ?>
                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?></p>

        <?php
    }
}
$commenttimestamp = strtotime("now");

$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
    $timestamp = date("l F d Y", $row['timestamp']);
    printf("<hr />");
    print("<p>" . stripslashes($row['comment']) . "</p>");
    printf("<p>Comment by <a href=\"%s\">%s</a> @ %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
    printf("<hr />");
}
?>

<form method="post" action="process.php">

<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />

<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">

<strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="25" /><br />

<strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="25" /><br />

<strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="25" value="http://" /><br />

<strong><label for="comment">Comment:</label></strong><br />
<textarea cols="25" rows="5" name="comment" id="comment"></textarea></p>

<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>

</form>

Update: Let’s add a snippet to the main page that both links the individual entry and gives a comment count.

Open your main blog page, and find this:

Posted on <?php echo $date; ?>

Right after that line we’ll put in this sql query:

$result2 = mysql_query ("SELECT id FROM php_blog_comments WHERE entry='$id'");

Now we’ll use mysql_num_rows() to count the results:

$num_rows = mysql_num_rows($result2);

Now $num_rows is the number of comments for this entry. Let’s print that and a link to our individual entry page (mine’s called journal.php, yours may not be):

<?php echo "<a href=\"journal.php?id=" . $id . "\">" . $num_rows . " comments</a>"; ?>

If you prefer, you can make that an if/else statement so that zero comments displays a different message, like so:

<?php if ($num_rows > 0) {
    echo "<a href=\"journal.php?id=" . $id . "\">" . $num_rows . " comments</a>";
}
else {
    echo "<a href=\"journal.php?id=" . $id . "\">Leave a comment</a>";
} ?>

You’ll also want to add this variable along with the others, if you haven’t already:

$id = $row['id'];

Now your whole main page should look like this (depending, once again, on whether you have password protection or not):

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

$sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";

$result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error());

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";

        printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

        printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
        print "<hr />";
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        <?php 

        $result2 = mysql_query ("SELECT id FROM php_blog_comments WHERE entry='$id'");
        $num_rows = mysql_num_rows($result2);

        if ($num_rows > 0) {
            echo "<a href=\"journal.php?id=" . $id . "\">" . $num_rows . " comments</a>";
        }
        else {
            echo "<a href=\"journal.php?id=" . $id . "\">Leave a comment</a>";
        } ?>

        <hr /></p>

        <?php
    }
}

?>

Now you should have a working comments system. Let me know if you have any problems or find any errors!