Specifications
Using PHP
P
ART I
50
Now that we know how to access and manipulate data entered in an HTML form, we can look
at ways of storing that information for later use. In most cases, including the example we
looked at in the previous chapter, you’ll want to store this data and load it later. In our case, we
need to write customer orders to storage so that they can be filled later.
In this chapter we’ll look at how you can write the customer’s order from the previous example
to a file and read it back. We’ll also talk about why this isn’t always a good solution. When we
have large numbers of orders, we should use a database management system such as MySQL.
Key topics you will learn about in this chapter include
• Saving data for later
• Opening a file
• Creating and writing to a file
• Closing a file
• Reading from a file
• File locking
• Deleting files
• Other useful file functions
• Doing it a better way: database management systems
• Further reading
Saving Data for Later
There are basically two ways you can store data: in flat files or in a database.
A flat file can have many formats but, in general, when we refer to a flat file, we mean a sim-
ple text file. In this example, we’ll write customer orders to a text file, one order per line.
This is very simple to do, but also pretty limiting, as we’ll see later in this chapter. If you’re
dealing with information of any reasonable volume, you’ll probably want to use a database
instead. However, flat files have their uses and there are some situations when you’ll need to
know how to use them.
Writing to and reading from files in PHP is virtually identical to the way it’s done in C. If
you’ve done any C programming or UNIX shell scripting, this will all seem pretty familiar
to you.
Storing and Retrieving Bob’s Orders
In this chapter, we’ll use a slightly modified version of the order form we looked at in the last
chapter. We’ll begin with this form and the PHP code we wrote to process the order data.
04 7842 CH02 3/6/01 3:37 PM Page 50