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.
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 <? echo $HTTP_USER_AGENT ?><BR> and coming from <? echo $REMOTE_ADDR ?> </BODY></HTML>
You should see something like the following in your browser window:
You are using Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) and coming from 207.164.141.23
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(empty($interest)) $interest=array(-1); ?> <FORM ACTION="form.php3" 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[]> <? for($i=0, reset($interest); $i<count($options); $i++){ echo "<OPTION"; if(current($interest)==$options[$i]) { echo " SELECTED "; next($interest); } echo "> $options[$i] "; } ?> </SELECT><BR> <INPUT TYPE=submit> </FORM> <? } if(!isset($first)) { show_form(); } else { if(empty($first) || empty($last) || count($interest) == 0) { echo "You did not fill in all the "; echo "fields, please try again<P> "; show_form($first,$last,$interests); } else { echo "Thank you, $first $last, you "; echo "selected ". join(" and ", $interest); echo " as your interests.<P> "; } } ?> </BODY></HTML>
There are a few things you should 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 that 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
(assuming the array is empty to begin with).
The final thing to note is the way we determine what to display. We
check if $first
is set. 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.
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, 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 all 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.php3" METHOD="POST"> 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().": "; echo mysql_error()."<BR>"; } } if($vote && $already_voted) { echo "<FONT COLOR=#ff0000>Hey, you voted "; echo "already! Vote ignored.</FONT><P> "; } else if($vote) { if(!mysql_db_query($db, "update $table set votes=votes+1 where name='$vote'")) { echo mysql_errno().": "; echo mysql_error()."<BR>"; } } $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 "<TABLE BORDER=0><TR><TH>Vote</TH>"; echo "<TH>Idea</TH><TH COLSPAN=2>Votes</TH>"; echo "</TR> "; while($row=mysql_fetch_row($result)) { echo "<TR><TD ALIGN=center>"; echo "<INPUT TYPE=radio NAME=vote "; echo "VALUE='$row[0]'></TD><TD>"; echo $row[0]."</TD><TD ALIGN=right>"; echo $row[1]."</TD><TD>"; 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> "; } echo "</TABLE> "; mysql_free_result($result); ?> <INPUT TYPE=submit VALUE="Submit idea and/or vote"> <INPUT TYPE=reset> </FORM> </BODY></HTML>
3.22.181.81