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, youll 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 well look at how you can write the customers order from the previous example
to a file and read it back. Well also talk about why this isnt 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, well write customer orders to a text file, one order per line.
This is very simple to do, but also pretty limiting, as well see later in this chapter. If youre
dealing with information of any reasonable volume, youll probably want to use a database
instead. However, flat files have their uses and there are some situations when youll need to
know how to use them.
Writing to and reading from files in PHP is virtually identical to the way its done in C. If
youve done any C programming or UNIX shell scripting, this will all seem pretty familiar
to you.
Storing and Retrieving Bobs Orders
In this chapter, well use a slightly modified version of the order form we looked at in the last
chapter. Well 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