Flat File Database Demo

Sections/Permalinks

Introduction

I received a query asking how to use PHP to read from a flat file database and output it as HTML. A 'flat file' is just another name for a plain text file. I was only too happy to help out, having used this technique over and over both at home and at work. The reason was that at work, we weren't allowed to use MySQL, the standard tool for web-based databases. I never learnt how to use it, instead learning enough basic PHP to code my own database from scratch. Everything I still do now runs off flat files. They are easy to manage because you can read them in any standard text editor, the files can be quite small and backing them up isn't a problem. Of course flat files won't match the built-in flexibility of something like MySQL, but you are free to program with them in any way you see fit. The only limit is your imagination and your coding skills.

Here is a basic demo showing a simple way to display the contents of a flat file database. You'll need a server running PHP. The demo only needs two files, plus there's nothing to set up on the server, unlike MySQL. The main file is a mix of PHP and HTML and should be saved with the extension ".php" so it will be parsed. The other file is your database. This is just a plain text file.

Next you can see the demo in action. I'll then list the exact code used and show you how it works. Feel free to copy the code and use it in your own projects.

What you see there is the raw contents of a typical flat file database. Each field is separated by a special character. In this case I'm using the pipe ("|") as it's rarely used in text. This character is known as a 'delimiter'. Whichever character you choose as a delimiter, you must make sure it will never appear in your text fields, otherwise the text will get cut off. If you need to use a character you've defined as a delimiter later on, then you can process the text before storing it in the database first, changing the delimiter to something harmless instead. Then just convert it back when reading from the database. But that's moving into advanced territory, so back to the simple stuff!

The database I've used simply shows the row and cell numbers in a table. We want to match these to a real table in HTML later, so we can be sure the script has worked properly. Any text you like can go inbetween each pipe symbol, so long as there are no linebreaks until the last field has been typed in. Each line in the database must go from left to right, no matter how long it gets, or the script won't work. (It may appear to flow over several lines in your text editor, if it has been set to wrap long lines.)

Now here is the PHP code used. It lives inside the HTML used to make up the web page. (PHP code can go anywhere you like in the HTML and is acted on first by the server, before the end result is passed to the browser. Just remember to open and close it with PHP tags, as below.)

The PHP Code

UPDATE 21st May 2010: the code below is subject to possible updates over time so check the actual demo itself for the latest code.

<?php

$fp = fopen('flat-file-data.txt','r');

if (!$fp) {echo 'ERROR: Unable to open file.</table></body></html>'; exit;}

$loop = 0;

while (!feof($fp)) {

$loop++;

$line = fgets($fp, 1024); //use 2048 if very long lines

$field[$loop] = explode ('|', $line);

echo '

<tr>

<td>'.$field[$loop][0].'</td>

<td>'.$field[$loop][1].'</td>

<td>'.$field[$loop][2].'</td>

<td>'.$field[$loop][3].'</td>

<td>'.$field[$loop][4].'</td>

<td>'.$field[$loop][5].'</td>

</tr>';

$fp++;

}

fclose($fp);

?>

I will next explain each line in detail:

Line 1 is the opening PHP tag. This tells the server to send everything after it (up to the closing PHP tag) to the PHP parser, which sits on the server. The parser processes all the programming instructions you have put in. The good thing about this is that the end user never sees the PHP code, only the resulting HTML.

The database shown earlier is opened for reading. The online PHP manual tells us on this page that 'r' means "Open for reading only; place the file pointer at the beginning of the file". There are many different settings you can use here, but we just want to read the file, not write to it.

If the file cannot be found, we need to generate an error. The PHP command exit is used to stop processing any more code.

A variable $loop is used for noting the database line numbers later on.

Now a loop is started to read the contents of the database. It is set to loop until the end of the file is reached.

The variable $loop is incremented by 1. This is similar to saying $loop = $loop + 1.

A variable $line grabs a line of the database up to 1,024 characters.

Six variables are chosen for each field, while the line of text is broken down by the delimiter. Because the pipe character was used, an extra slash is needed before it. Normal alphabetical characters and punctuation might not need the slash. The line is exploded into an array using the pipe symbol as the delimiter.

Now each field is in a variable an array, we can output the contents to the browser. To do this, echo is used.

An opening table row tag is echoed first.

Note: If echo uses speech marks around the text that follows, then any speech marks within the text have to be 'escaped' by using a slash before each one. With large amounts of text, this becomes a big hassle. But using apostrophes instead removes the need for slashes. The only drawback is that variables have to be outside the echoed text. To echo them as well, a dot is used to join the text and the variables together.

You can include linebreaks within the echo statement and include HTML tags as well.

Here I have put each field inside a table cell tag.

The number of variables array entries used matches the number of fields in your database, but you can miss out fields if you only want to read the first few.

If you want to sort the fields before displaying them, then a second array can be used.

The variable names can be anything you want. I try to match them to the database, so I might use $tel, $fax and $email, for instance. (This no longer applies.)

A closing table row tag is echoed last.

The 'file pointer' is incremented by one, so the loop will start reading from the next line of the database.

This closes the loop.

Now the file needs to be closed.

Finally we need to come out of PHP so the server knows to stop parsing your file at this point. So this line has the closing PHP tag. You can keep going in and out of PHP many times during a web page file, but if you find yourself doing this with only a little bit of HTML inbetween each script, consider staying inside PHP and echoing the HTML instead.

Summary

What we have here is a very basic script that reads a flat file database just by using a loop, then breaking down the text into variables and spitting them out. You can build on this simple code in many ways. Your HTML table can become dynamic, so the user can sort it by clicking on each column header. Or you can implement a crude search form that works by reading through the database until it finds the text you need. Some web designers swear by flat file databases, claiming them to be way smaller than their MySQL equivalents. They are also a great way to learn PHP. I hope you will find my code useful. What can you do with it?

Chris Hester:
Yes, anything is possible when you get into writing the file, not just reading it. You can read the data, put it into an array, sort it, remove or add text, then simply write back to the file. (PHP has a great file method which allows you to set the contents of the file to zero, so you can easily overwrite it.) Or you can append new lines to the end of the existing file.

A page with a form might be used to open the file and put the contents into a text area. Then it can write the changes back to the file. Obviously some security is needed there, like a password in the form, so no-one else can use it.

If you are only changing one line though, I guess this method isn't as flexible as MySQL. What you can do is use a program like Access, then export the tables as delimited text. That's what I do at work. We have several pages that are generated from a couple of flat files. All I need to do to update the pages is simply export the files from Access again and upload them, replacing the ones on the server.

James Welch:
Im running a web design directory site using this nice bit of code - simple and very effective. No db whatsoever, just php and the code above - created over 1000 pages of web designers info.

Michael:
I have a question about this statement: If you want to sort the fields before displaying them, then a second array can be used.
I'm not much of a programmer and I'm stumbling over the who array/sort thing. What would the field sort look like in your example?

Useful Info

Disclaimer

Some links on this website lead to information provided by external services not under my control, therefore I am not responsible for the content or accuracy of the linked information.

All code examples are not guaranteed 100% free from bugs and/or mistakes. Use them at your own risk. I do not take any blame should a problem occur relating to use of code on this site given as an example for your own use. Such code has been tested and found to work for me, but I cannot vouch for other computer systems (existing now, or in the future) which it may be used on, or changes you introduce yourself based on my code.