• Join over 1.2 million students every month
  • Accelerate your learning by 29%
  • Unlimited access from just £6.99 per month
Page
  1. 1
    1
  2. 2
    2
  3. 3
    3
  4. 4
    4
  5. 5
    5
  6. 6
    6
  7. 7
    7
  8. 8
    8
  9. 9
    9
  10. 10
    10
  11. 11
    11
  12. 12
    12
  13. 13
    13
  14. 14
    14
  15. 15
    15
  16. 16
    16
  17. 17
    17
  18. 18
    18
  19. 19
    19
  20. 20
    20

To highlight how easy it is to do database backed websites I wrote a simple guestbook using PHP

Extracts from this document...

Introduction

The Guestbook

To highlight how easy it is to do database backed websites I wrote a simple guestbook using PHP. The code will be examined here to explain how the PHP code works and why I did certain things. One of my goals in writing database backed websites is to keep related pages and functions as simple as possible, but where possible to use a single file to make troubleshooting easier. This might make things more confusing at first, but it will work better in the long term.

The application is very simple. When you go to the page it loads the "Add A Message" form and then connects to the database to get all the guestbook entries. Once is has selected the data it builds the html to display the output and delivers it to the browser.

When someone fills out the form and hits the submit button, the form action reloads the page, adds the data to the database, then selects all the data again including the new entry and builds the html to display the output and delivers it to the browser.

The code I have commented on this page is available in my File Area. In my comments I have used teal to represent comments, red to indicate PHP code and blue to indicate HTML.

Getting Started

The first item of note about PHP is how the server knows whether a bit of text in the file is PHP or HTML. The server is alerted to begin processing PHP code when it encounters a <?. It continues to process the text as PHP code until it encounters a ?>. The wonderful part about PHP is that you can break into and out of PHP processing mode for little snippets of code.

...read more.

Middle

Fgdgggggggggggggggggggg

<html>
<head><title>Guest book - display the info&lt;/title>
&lt;/head> 

<body bgcolor=#ffffff>

<?php

if (empty($srt)) {
 
$srt='TimeStamp';
}

if (empty(
$offset)) {
 
$offset='0';
 }

echo 
"<h2>Entries from the guest book sorted by $srt&lt;/h2>";


    
mysql_connect() or die ("Problem connecting to DataBase");
    
$query "SELECT * FROM visitors order by $srt limit $offset,10";
    
$result mysql_db_query("guest_book"$query); 

    if (
$result) {        //Print results in table

  
echo "<table width=90% align=center border=1><tr>
    <td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=TimeStamp\">Visit time and date&lt;/a>&lt;/td>
    <td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Name\">User 
Name&lt;/a>&lt;/td>
    <td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Last\">Last 
Name&lt;/a>&lt;/td>
    <td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=email\">Email&lt;/a>&lt;/td>
    &lt;/tr>"
;

        while (
$r mysql_fetch_array($result)) {       
            
$ts $r["TimeStamp"];
            
$name $r["Name"];
            
$last $r["Last"];
            
$email $r["email"];
            
$comment $r["comment"];
            echo 
"<tr>
            <td>$ts&lt;/td>
            <td>$name&lt;/td>
            <td>$last&lt;/td>
            <td>$email&lt;/td>&lt;/tr>
                <tr>    <td colspan=4 bgcolor=\"#ffffa0\">$comment&lt;/td>
        &lt;/tr>"
;
        }       
//End while loop
        
echo "&lt;/table>";
    }          
//End if true  
     
else {           //Begin if false
        
echo "error.";
    }           
//end if false
    
mysql_free_result($result);

 
$next=$offset+'10';   //View next or previous entries
 
$prev=$offset-'10';

  
$query "SELECT * FROM visitors";
  
$res mysql_db_query("guest_book"$query); 
  
$num=mysql_num_rows($res);

echo 
"<table align=center><tr>";

if (
$prev>='0'
  {
    echo 
"<form method=\"post\">"
    echo 
"<input type=hidden name=offset value=$prev>";
    echo 
"<input type=hidden name=srt value=$srt>";
    echo 
"<td align=center><input type=submit value='Previous Entries'>&lt;/td>";
    echo 
"&lt;/form>";
  }

if (
$num>=$next
  {
    echo 
"<form method=\"post\">";
    echo 
"<input type=hidden name=offset value=$next>";
    echo 
"<input type=hidden name=srt value=$srt>";
    echo 
"<td align=center><input type=submit value='Next Entries'>&lt;/td>";
    echo 
"&lt;/form>";
  }

echo 
"&lt;/tr>&lt;/table>";

include (
'links.x');

?>


&lt;/body>
&lt;/html>

As you can see, I used the mysql_connect function with no information inside the (). If you use a remote computer of a unix based php/mysql you have to use a slightly different syntax: mysql_connect ('servername','your_username','your_password');

Well, this page is rather complex at first glance, but I will try my best explain it.

At the top of the page you can see the following section:

if (empty($srt)) {
 $srt='TimeStamp';
}

if (empty($offset)) {
 $offset='0';
 }

Those two commands check whether I transferred data into the page or not, and if not it sets two default values that will be used later on. To check if I transferred any variables, I used the empty ($variable) command which returns false if $variable is set and has a non-empty or non-zero value; and returns true otherwise.

Once I set default values to my variables, I can query the MySQL database with:

$query = "SELECT * FROM visitors order by $srt limit $offset,10";
$result = mysql_db_query("guest_book", $query); 

Notice that I used the two variables in this command (which at start hold the default values set previously). The order by $srt sorts selection by $srt (which holds TimeStamp as default) and limit $offset,10 gets the first 10 results starting with $offset.

The next section prints the results in a formatted table as I explained this in my
Beginners Guide to PHP/MySQL. The only interesting thing is the sort options I added with:

echo "<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=TimeStamp\">Visit time and date&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Name\">User Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Last\">Last Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=email\">Email&lt;/a>&lt;/td>&lt;/tr>";

Here you can see how to transfer variables with links and not forms. I used the srt variable to transfer the sorting method to the page itself (or any other page for that matter).

Now I define two variables to be used later as new offsets for the next and previous entries on the table:

$next=$offset+'10'; 
$prev=$offset-'10';

Next I need to know the total number of entries on the table in order to see if I have more results or not:

$query = "SELECT * FROM visitors";
$res = mysql_db_query("guest_book", $query); 
$num=mysql_num_rows($res);

I select all the rows from the table, and use the mysql_num_rows($res) which returns the number of rows in a result set.

Now consider the following php script:

if ($prev>='0') 
  {
    echo "<form method=\"post\">"; 
    echo "<input type=hidden name=offset value=$prev>";
    echo "<input type=hidden name=srt value=$srt>";
    echo "<td align=center><input type=submit value='Previous Entries'>&lt;/td>";
    echo "&lt;/form>";
  }

if ($num>=$next) 
  {
    echo "<form method=\"post\">";
    echo "<input type=hidden name=offset value=$next>";
    echo "<input type=hidden name=srt value=$srt>";
    echo "<td align=center><input type=submit value='Next Entries'>&lt;/td>";
    echo "&lt;/form>";
  }

Here I have two "if" conditions which check whether I have more entries in the table, whether I have previous entries or none. The script creates two small forms that transfer to the php script both the offset for the table and the sorting method.

At the end of the page I just add the links.x which holds any necessary additional links and voila.

Adding entries to the table:



Well, this one is easy. First I create a small form with the fields I want to use:

<html>
<head><title>Adding entry to guest book&lt;/title>
&lt;/head> 

<body bgcolor=#ffffff>

<h2>Add an entry&lt;/h2>

<form method="post" action="add2tbl.php3">
<table width=90% align=center>
<tr><td>Name:&lt;/td><td><input type=text name='name' size=40 
maxlength=100>&lt;/td>&lt;/tr>
<tr><td>Last Name:&lt;/td><td><input type=text name='last' size=40 maxlength=100>&lt;/td>&lt;/tr>
<tr><td>email:&lt;/td><td><input type=text name='email' size=40 maxlength=100>&lt;/td>&lt;/tr>
<tr><td>Your Comment:&lt;/td><td><textarea name=comment rows=4 
cols=60>&lt;/textarea>&lt;/td>&lt;/tr>
<tr><td>&lt;/td><td><input type=submit>&lt;/td>&lt;/tr>
&lt;/table>
<input type=hidden name=timestamp 
<?php $dte=date("d/m/Y H:i:s"); 
echo 
"value='$dte'";?>><br>
&lt;/form>
<?php include ('links.x');?>
&lt;/body>
&lt;/html>

The script itself is rather simple to anyone familiar with forms. The only interesting thing is the TimeStamp I used in hidden mode:

<input type=hidden name=timestamp <?php $dte=date("d/m/Y H:i:s"); 
echo 
"value='$dte'";?>><br>
&lt;/form>

I just used the php date function to create a time stamp and use it as the fields default value. This enables me to make sure that if I want to delete or modify an entry I have a unique value to match.

All those values are transferred to another php script called
add2tbl.php3 which inserts the data into the table:

<?
 
if ($name
   {
    
mysql_connect() or die ("Problem connecting to DataBase");
    
$query "insert into visitors values 
('$timestamp','$name','$last','$email','$comment')"
;
    
$result mysql_db_query("guest_book"$query); 
    echo 
'Thank you your input.<br><p>&lt;/p>';
   }

 include (
'links.x');
?>

Well, that's it for now.

...read more.

Conclusion



if (!$end || $start<=0) { $start=1; }
if (!$end) { $end=10; }
if ($end<$start) { $end=$start+1; }
$show=$end - $start;

//Get records from file into array
      $records = get($start, $end);

//For each record get each field
      foreach ($records as $rec) {
           $tmp = explode($separator, $rec);
           $msg = $tmp[0];
           $author = $tmp[1];
           $email = $tmp[2];
           $homepage = $tmp[3];

//=================================
//Outputting
?>
<HR>
Author: <?=$author?><br>
Email: <?=$email?><br>
Homepage: <?=$homepage?><br>
Text: <?=$msg?><br><br>
<?
      }

//Pagination
if ($start>$show) {
      $start-=$show;
      $end-=$show;
      print "<a href=gb.php?start=$start&end=$end>Prev $show</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

      if (count($records)!=0) {
      $start+=$show*2;
      $end+=$show*2;
      print "<a href=gb.php?start=$start&end=$end>Next $show</a>";
}
else {
      print "No more records found !";
}
}
else {
      $start+=$show;
      $end+=$show;
      print "<a href=gb.php?start=$start&end=$end>Next $show</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
}
?>


How to use it...
First, remember to use HTML form that is shown in top part of this text. Second, to see the contents of the guestbook, you can create a regular link to the file:

<a href=gb.php>Guestbook</a>

If you want to have a certain number of records to be shown on each page of the guestbook, you can use this parameters for the script:
start: means number of the first record
end: means number of the last record
Example:
gb.php?start=1&end=10
If you want to configure this script with the design of your page you can insert any HTML code before the code (I mean before the first '<?'). And also you can add a footer after the last line of the file.

...read more.

This student written piece of work is one of many that can be found in our University Degree Computer Science section.

Found what you're looking for?

  • Start learning 29% faster today
  • 150,000+ documents available
  • Just £6.99 a month

Not the one? Search for your essay title...
  • Join over 1.2 million students every month
  • Accelerate your learning by 29%
  • Unlimited access from just £6.99 per month

See related essaysSee related essays

Related University Degree Computer Science essays

  1. Marked by a teacher

    UK Copyright and File Sharing

    5 star(s)

    I think something to do with one IP address meaning you can't get found out. Q. Do you think the government can do anything to reduce file sharing, or do you think it can't be prevented? If you think it can be prevented, what measures do you think they should take?

  2. Traffic Light Simulation and Machine Code Program.

    On line resources usually need interaction with the user. OP Code A binary code that the CPU can interpret as a command. These correspond to commands like MOV and ADD. Overflow Flag This is set if the result of the previous calculation was too big to fit the register.

  1. The project explains various algorithms that are exercised to recognize the characters present on ...

    Figure 5.2 Simulation Results for Case 2 Number Reference Number Matching Ratio % 0 31 85 1 4 92 2 10 89 3 17 100 4 33 96 5 35 84 6 26 92 Table 5.3 Case 2 Simulation Results for Character Recognition The tabulated results above provide us with the following three fields.

  2. A bucketing framework for Database security

    Another challenging part of our paper is the generalization of QOB for two attributes by using along other things the Hilbert curve. 3. OUR IMPLEMENTATION 3.1 Technologies We have decided to use Java because it is the programming language that we know the best. We naturally used Eclipse (cf. [2])

  1. IP network design

    Care is needed when selecting the encryption mechanism, to ensure that it is not easy to crack. For example, the wired equivalent privacy (WEP) system of 802.11 standard wireless Ethernet systems has been shown to be relatively straightforward to crack.

  2. So in order to understand what the main areas where organisation should be aware ...

    (http://searchsecurity.techtarget.com/home/0,289692,sid14,00.html [accessed 15 November 2005]) Why is footprinting necessary? Footprinting is necessary to systematically and methodically ensure that all pieces of in-formation related to the aforementioned technologies are identified. Without a sound methodology for performing this type of reconnaissance, you are likely to miss key pieces of information related to a specific technology or organization.

  1. Table of contents

    o Redundancy (by having more than one on the same work) Ants Colony and Multi-Agents Individual ants are simple insects with limited memory and capable of performing simple actions. However, an ant colony expresses a complex collective behavior providing intelligent solutions to problems such as carrying large items, forming bridges

  2. At the end of our audit of service in &amp;quot;U Szwejka&amp;quot; Restaurant we would ...

    Shorter people had to lean over to the table o A great place to spend some time with friends o funny and rivet posters and banners in Czech language o clean and tidy Employees and service personnel - Roles and requirements, and fit with customer needs o Manager (no contact)

  • Over 160,000 pieces
    of student written work
  • Annotated by
    experienced teachers
  • Ideas and feedback to
    improve your own work