Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

seems more readable to me. You should avoid mysql_result, since this function does
a costly lookup into a two-dimensional array.


When no more rows remain, FALSE will be returned. Capitalizing on this behavior, I put
the fetch of the row inside a while loop. I create a row in the HTML table, printing object
properties inside the table cells. When no rows remain, I close the table. I don't bother to
close the connection to the database because PHP will do this automatically.


This is an extremely simply example, but it touches on all the major features of working
with a database. Since each row is created in a loop, each is uniform. If the data change,
there is no need to touch the code that turns it into HTML. You can just change the data
in the database.


A good example of this technique in action is the Random Band Name Generator
<http://www.leonatkinson.com/random >, which creates random band names
from a table of words, stored in a MySQL database to which anyone can add. Each
refresh of the page fetches another ten names.


Tracking Visitors with Session Identifiers


As Web sites evolve into Web applications, the problem of maintaining state arises. The
issue is that, from page to page, the application needs to remember who is visiting the
page. The Web is stateless. Your browser makes a connection to a server, requests one or
more files, and then closes the connection. Five minutes later when you click to a
connecting page, the routine happens all over again. While a log is kept, the server
doesn't remember you. Any information you gave it about yourself three pages back may
be saved somewhere, but it's not associated with you after that.


Imagine a wizardlike interface for ordering a pizza. The first screen asks you how many
pizzas you want. Then you go through a page for each pizza, picking toppings and type of
crust. Finally a page asks for your name and number so that your order can be emailed to
the nearest pizza parlor. One way to handle this problem is to pass all the information
gathered up to that point with each form submission. As you go from page to page, those
data grow and grow. You're telling the server a partial version of your order many times.
It works, but it's definitely wasteful of network bandwidth.


Using a database and a session identifier, you can store information as it becomes
available. A single identifier is used as a key to the information. Once your script has the
identifier, it can remember what has gone on before.


How the script gets the identifier is another issue. You have two choices. One is to pass
the identifier as a variable inside every link or form. In a form this is simple to do with a
hidden variable. In a link you have to insert a question mark and a variable definition. If
your session ID is stored in a variable called session, then you might write something
like

Free download pdf