Archive for April, 2003

Viewing our comments

Tuesday, April 1st, 2003

In order to view our comments, we need some php code to read the database table we just created. Below is a source listing of a PHP script that will open the table and display all the records. A real version of the script that executes can be found here

<html>
<head>
<title>Virgil's Comments</title>
</head>
<body>
<h1>Virgil's Comments</h1>
<hr>
<?php

$linkID mysql_pconnect("localhost:3306","user","password");
mysql_select_db("database",$linkID);

if($linkID != FALSE)
{
    
$query "SELECT ID, PostID, Name, Email, Comment, TimeEntered from comments ORDER BY PostID, ID";

    $resultID mysql_query($query$linkID);

    if($resultID != FALSE)
    {
        while (list(
$ID$PostID$Name$Email$Comment$TimeEntered) = mysql_fetch_row($resultID))
        {
            print 
"<table>";
            print 
"  <tr>";
            print 
"    <td>$TimeEntered - <b>$Name</b> - [<a href = "mailto:$Email">email</a>] - [<a href = "http://ncfolk.net/virgil" target="_blank">homepage</a>]</td>";
            print 
"  </tr>";
            print 
"  <tr><td>&nbsp;</td></tr>";
            print 
"  <tr><td><pre>$Comment</pre><br /></td></tr>";
            print 
"</table>";
            print 
"<hr>";
        }
    }
    else
    {
        print 
"Query failed";
        print 
"<p>Messages: " mysql_error($linkID) . "</p>";
    }
    
mysql_close($linkID);
}
else
{
    print 
"Error: Could not connect to database.";
}
?>

</body>
</html>

The basic logic is to open the database (the mysql_pconnect() call), select a database, query the database, and then loop through the results that are returned. For each result record, the data is formatted and printed in an HTML table. Some basic error handling code is provided.

NOTE: You will have to replace the “user”, “password”, and “database” with values appropriate for your system.

Next time we will look at how to gather information in an HTML form so we can store comments in the database.