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

(singke) #1

The next logical step is to add another table for storing the information you need to know
about the person browsing your site. One of the columns should be for storing the session
identifier from the session table. I'll leave this as an exercise for you.


Storing Content in a Database


Information stored in a database is not limited to short strings, like the 32-character item
name from Listing 17.3. You can create 64K blobs, which are enough to store a good-
sized Web page. The advantage here is that pages exist in a very structured environment.
They can be identified by a number, and relationships can be drawn between them using
only these numbers. The disadvantage is that, since the information is now in a database,
you can't just load the file into your favorite editor. You have to balance the costs and
benefits; most Web sites don't need every piece of content stored in a database.


A situation where it makes a lot of sense to put the content in a database is a Bulletin
Board System, or BBS. The system stores messages, which are more than just Web
pages. Each message has its own title, creation time, and author. This structure can be
conveniently wrapped up into a database table. Furthermore, since each message can be
given a unique identifier, we can associate messages in a parent-child tree. A user can
create a new thread of discussion that spawns many other messages. Messages can be
displayed in this hierarchical structure to facilitate browsing.


As with all database-related systems, the first step is to create a table. Listing 17.6
creates a table for storing messages. Each message has a title, the name of the person who
posted the message, when the message was posted, a parent message, and the body of
text. The parent ID might be zero, in which case we understand the message to be the
beginning of a thread. The body doesn't have to be plain text. It can contain HTML. In
this way it allows users to create their own Web pages using their browsers.


The script in Listing 17.7 has two modes: listings message titles and viewing a single
message. If the messageID variable is empty, then a list of every message in the system
is shown organized by thread. This is accomplished by the showMessages function.


You might want to turn back to Chapter 4, "Functions," specifically the section on
recursion. The showMessages function uses recursion to travel to every branch of the
tree of messages. It starts by getting a list of all the messages that have no parent. These
are the root-level messages, or beginnings of threads. After showing each root-level
message, showMessages is called for the thread. This process continues until a
message is found with no children. UL tags are used to display the message titles. The
indention aids the user in understanding the hierarchy.


Listing 17.6 Create Message Table

Free download pdf