<HTML>
 <HEAD>
  <TITLE>
   Guestbook 1.0
  </TITLE>
 </HEAD>
 <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
 <? //some global variables
   function viewEntries()
   {
   $username="root";
   $password="redrum1";
   $db="guestbook";
   $table="simple_guestbook";
   $db_host="localhost";
   $connection=mysql_connect($db_host,$username,$password);
   $viewquery="SELECT * FROM $table";
    // print the entries in a table
    $result=mysql_db_query($db,$viewquery);
    if (!$result)
    {
     echo "<CENTER><H2>No entries yet</H2></CENTER>";
     echo "Result is $result<BR>";
     echo "Query was $viewquery<BR>";
     echo "Connection was $connection<BR>";
    }
    else
    {
     echo "<CENTER><TABLE COLS=\"2\" BORDER=\"0\">";
     while ($row=mysql_fetch_row($result))
     {
      $date=$row[2];
      $user_name=$row[3];
      $user_email=$row[4];
      $message=$row[5];
      // print the tablecell
      echo "<TR><TD>Name:</TD><TD>$user_name</TD></TR>\n";
      echo "<TR><TD>Email:</TD><TD><A HREF=\"mailto:$user_email\">$user_email</A></TD></TR>\n";
      echo "<TR><TD>Date:</TD><TD>$date</TD></TR>\n";
      echo "<TR><TD>Message:</TD><TD>$message</TD></TR>\n";
    } //end while
    echo "</TABLE></TABLE>\n";
   } //end else
   mysql_close($connection);
  } //end function
  function getNewMessageId()
  {
   $username="root";
   $password="redrum1";
   $db="guestbook";
   $table="simple_guestbook";
   $db_host="localhost";
   $connection=mysql_connect($db_host,$username,$password);
   $maxquery="SELECT MAX(message_id) FROM $table";
   $result=mysql_db_query($db,$maxquery);
   if (!$result) {
    echo mysql_errno().":";
    echo mysql_error()." has occured in getNewMessageID()<BR>";
  }
  else
  {
   $row=mysql_fetch_row($result);
   $id=$row[0];
   $id++;
   mysql_close($connection);
   return $id;
  } //end if-else
 } //end function
 function printForm()
 { ?>
 <FORM ACTION="guestbook.php" METHOD="POST">
 <TABLE COLS="2" BORDER="2">
 <TR><TD>Name:</TD><TD><INPUT TYPE="TEXT" NAME="name"></TD></TR>
 <TR><TD>Email:</TD><TD><INPUT TYPE="TEXT" NAME="email"><TD></TR>
 <TR><TD>Message:</TD><TD><TEXTAREA NAME="message" COLS="40" ROWS="5"></TEXTAREA></TD></TR>
 </TABLE>
 <CENTER>
  <INPUT TYPE="SUBMIT" VALUE="Add entry">
 </CENTER>
 </FORM>
 <? } 
 function insertEntry()
 {
   $username="root";
   $password="redrum1";
   $db="guestbook";
   $table="simple_guestbook";
   $db_host="localhost";
   $connection=mysql_connect($db_host,$username,$password);
   $new_id=getNewMessageId();
   $insertquery="INSERT INTO $table VALUES ($new_id,0,CURDATE(),'$name','$email','$message')";
   $result=mysql_db_query($db,$insertquery);
   if (!$result) {
    echo mysql_errno().":";
    echo mysql_error()." has occured in getNewMessageID()<BR>";
   } //end if
   mysql_close($connection);
 } //end insertEntry
 ?>
 <H1>Guestbook</H1>
 <? if (!$message) { 
    viewEntries();
 } else {
   insertEntry();
   viewEntries();
 } ?>
 <HR>
 <? printForm() ?> 
 </BODY>
</HTML>
