A Simple Flat-file Database

For small website applications, it may be practical to use a flat-file database. An advantage is that data and executable files are stored together. The website can be zipped for uploading to a server and unzipped for saving as a backup.

This example is coded in PHP, with database records as text files. An arbitrary string of characters is used as a field delimiter, and records are organized into folders that represent tables. As a convention, I use a file called 'data' for all the table folders in the application.

The following example includes a single table, the 'products' table, as well as code to read and update the records in this table:

 File structure for website

Contents of the 'data' folder:

 contents of data folder

Individual product records within the 'data/products folder, where the file name serves as the primary key for each record:

 products folder

Records are divided into individual fields by arbitrary delimiter characters, ("XQX" for the example). Each table is represented by an array that defines the record fields for that table.


$dl1 = "XQX";
$dbtables = array (
"products" => array ("name", "price", "package", "status", "source")

The contents of 001.txt:
Backyard FavoriteXQX12XQXOne PoundXQXcurrentXQXBobcat's Red Mill

Records can be read using the readDatabaseRecord function:

function readDatabaseRecord($table, $recordid) {

global $dbtables;
global $dl1, $dl2;

//Initialize record
$record = array();
foreach ($dbtables[$table] as $label) {
$record[$label] = "";
if ($recordid!== "") {
$filename = "data/" . $table . "/" . $recordid . ".txt";
if (file_exists($filename)) {
$string = file_get_contents ($filename);
$array1= explode ($dl1, $string);
foreach ($dbtables[$table] as $id => $label) {
$record[$label] = "";
if (array_key_exists ($id, $array1)) {
$record [$label] = $array1[$id];


return $record;

Records can be written using writeDatabaseRecord:

function writeDatabaseRecord ($table, $record, $recordid) {

global $dl1, $dl2;

$filename = "data/" . $table . "/" . $recordid . ".txt";
$newstring = implode ($dl1, $record);
file_put_contents ($filename, $newstring);

Records can be deleted using moveToTrash:

function moveToTrash ($table, $recordid) {
$oldfilename = "data/" . $table . "/" . $recordid . ".txt";
$newfilename = "data/trash/" . $table . "----" . $recordid. ".txt";
if (file_exists ($oldfilename)) {
rename ($oldfilename, $newfilename);

Leave a comment