home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomeWebmaster in a Nutshell, 3rd EditionSearch this book

16.12. Examples

The best way to understand the power of PHP is to examine some real examples of PHP in action, so we'll look at some common uses of PHP in this section.

16.12.1. Showing the Browser and IP Address

Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:

<html><head><title>PHP Example</title></head>
<body>
   You are using 
    <?php echo $_SERVER['HTTP_USER_AGENT'] ?>
   <br />
   and coming from 
    <?php echo $_SERVER['REMOTE_ADDR'] ?>
</body></html>

You should see something like the following in your browser window:

You are using Mozilla/5.0 (X11; U; Linux i686; en-US; 
rv:1.1b) Gecko/20020722
and coming from 127.0.0.1

16.12.2. Intelligent Form Handling

Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:

<html><head><title>Form Example</title></head>
<body>
<h1>Form Example</h1>
<?
function show_form($first="", $last="", $interest="") {
 $options = array("Sports", "Business", "Travel", "Shopping", "Computers");
 if(!is_array($interest)) $interest = array( );
 ?>
 <form action="form.php" method="POST">
 First Name:
 <input type="text" name="first" 
        value="<?echo $first?>">
 <br />
 Last Name:
 <input type="text" name="last" 
        value="<?echo $last?>">
 <br />
 Interests:
 <select multiple name="interest[ ]">
 <?php
  foreach($options as $option) {
   echo "<option";
   if(in_array($option, $interest)) {
    echo " selected ";
   }
   echo "> $option</option>\n";
  }
 ?>
 </select><br />
 <input type=submit>
 </form>
<?php } // end of show_form( ) function

if($_SERVER['REQUEST_METHOD']!='POST') {
 show_form( );
} else {
 if(empty($_POST['first']) || 
    empty($_POST['last'])  ||
    empty($_POST['interest'])) {
  echo "<p>You did not fill in all the fields,";
  echo "please try again</p>\n";
  show_form($_POST['first'],$_POST['last'], $_POST['interest']);
 }
 else {
  echo "<p>Thank you, $_POST[first] $_POST[last], you ";
  echo 'selected '. join(' and ', $_POST['interest']);
  echo " as your interests.</p>\n";
 }
}
?>
</body></html>

There are a few things to study carefully in this example. First, we have isolated the display of the actual form to a PHP function called show_form(). This function is intelligent, in that it can take the default value for each of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature to redisplay the form with whatever values the user has already entered. This means the user only has to fill the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all the fields.

Notice how the file switches back and forth between PHP code and HTML. Right in the middle of defining our show_form() function, we switch back to HTML to avoid having numerous echo statements that just echo normal HTML. Then, when we need a PHP variable, we switch back to PHP code temporarily, just to print the variable.

We've given the multiple-choice <select> element the name interest[ ]. The [ ] on the name tells PHP that the data coming from this form element should be treated as an auto-indexed array. This means that PHP automatically gives each element the next sequential index, starting with 0 (assuming the array is empty to begin with).

The final thing to note is the way we determine what to display. We check if the SERVER variable REQUEST_METHOD is set to POST. If it isn't, we know that the user has not submitted the form yet, so we call show_form() without any arguments. This displays the empty form. If $first is set, however, we check to make sure that the $first and $last text fields are not empty and that the user has selected at least one interest.

16.12.3. Web Database Integration

To illustrate a complete database-driven application, we are going to build a little web application that lets people make suggestions and vote on what you should name your new baby. The example uses MySQL, a fast and easy to configure database (see http://www.mysql.com), but it can be changed to run on any of the databases that PHP supports.

The schema for our baby-name database looks like this:

CREATE TABLE baby_names (
  name varchar(30) NOT NULL,
  votes int(4),
  PRIMARY KEY (name)
);

This is in MySQL's query format and can be used directly to create the actual table. It simply defines a text field and an integer field. The text field is for the suggested baby name and the integer field is for the vote count associated with that name. We are making the name field a primary key, which means uniqueness is enforced, so that the same name cannot appear twice in the database.

We want this application to do a number of things. First, it should have a minimal check that prevents someone from voting many times in a row. We do this using a session cookie. Second, we want to show a fancy little barchart that depicts the relative share of the votes that each name has received. The barchart is created using a one pixel by one pixel blue dot GIF image and scaling the image using the height and width settings of the HTML <img> tag. We could also use PHP's built-in image functions to create a fancier-looking bar.

Everything else is relatively straightforward form and database work. We use a couple of shortcuts as well. For example, instead of reading all the entries from the database and adding up the votes in order to get a sum (which we need to calculate the percentages), we ask MySQL to do it for us with its built-in sum( ) function. The part of the code that displays all the names and their votes along with the percentage bar gets a little ugly, but you should be able to follow it. We are simply sending the correct HTML table tags before and after the various data we have fetched from the database.

Here's the full example:

<?
  if($vote && !$already_voted) 
    SetCookie('already_voted',1);
?>
<html><head><title>Name the Baby</title>
</head><h3>Name the Baby</h3>
<form action="baby.php" method="POST">
<p>Suggestion: 
<input type="text" name="new_name"></p>
<input type="submit" 
       value="Submit idea and/or vote">
<?
 mysql_pconnect("localhost","","");
 $db = "test";
 $table = "baby_names";

 if($new_name) {
  if(!mysql_db_query($db, "insert into $table 
      values ('$new_name',0)")) {
    echo mysql_errno( ).': '.
         mysql_error( )."<br />\n";
  }
 }
 if($vote && $already_voted) {
  echo '<p><b>Hey, you voted already ';
  echo "Vote ignored.</b></p>\n";
 }
 else if($vote) {
  if(!mysql_db_query($db, 
       "update $table set votes=votes+1 
        where name='$vote'")) {
   echo mysql_errno( ).': '.
        mysql_error( )."<br />\n";
  }
 }
 $result=mysql_db_query($db, 
     "select sum(votes) as sum from $table");
 if($result) {
  $sum = (int) mysql_result($result,0,"sum");
  mysql_free_result($result);
 }

 $result=mysql_db_query($db, 
   "select * from $table order by votes DESC");
 echo <<<EOD
  <table border="0"><tr><th>Vote</th>
  <th>Idea</th><th colspan="2">Votes</th>
  </tr>
EOD;
 while($row=mysql_fetch_row($result)) {
  echo <<<FOO
   <tr><td align="center">
   <input type="radio" 
          name="vote" value="$row[0]"></td>
   <td>$row[0]</td>
   <td align="right">$row[1]</td>
   <td>
FOO;
  if($sum && (int)$row[1]) {
   $per = (int)(100 * $row[1]/$sum);
   echo '<img src="bline.gif" height=12 ';
   echo "width=$per> $per %</td>";
  }
  echo "</tr>\n";
 }
 echo "</table>\n";
 mysql_free_result($result);
?>
<input type="submit" 
       value="Submit idea and/or vote" />
<input type="reset" />
</form>
</body></html>


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru