Monday, July 6, 2009

Overview of File Processing

There are three steps to writing data to a file:
1. Open the file. If the file doesn’t already exist, it will need to be created.
2. Write the data to the file.
3. Close the file.
Similarly, there are three steps to reading data from a file:
1. Open the file. If the file can’t be opened (for example, if it doesn’t exist), we need
to recognize this and exit gracefully.
2. Read data from the file.
3. Close the file.
When you want to read data from a file, you have choices about how much of the file to
read at a time.We’ll look at each of those choices in detail.
For now, we’ll start at the beginning by opening a file.

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
simple text file. In this example, we’ll write customer orders to a text file, one order per
line.
52 Chapter 2 Storing and Retrieving Data
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 Data

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
n Saving data for later
n Opening a file
n Creating and writing to a file
n Closing a file
n Reading from a file
n File locking
n Deleting files
n Other useful file functions
n Doing it a better way: database management systems
n Further reading