Simple Flat-File Database Tutorial Using PHP

2018-10-16

Do you need a way to keep track of information on your website without the overhead of a relational database?  The following  example shows a flat file database that includes a single table:  "Cat".

 This is how we would like to display individual cat records in the 'cats' table:

example of cats database

Files and folders we will need to manage our Cats database:

flat file structure

After we have added some records  the contents of  the 'cats' folder will look like this:

 

screenshot of individual records

The record for 'Snowball' in 'cats/showball.txt'  will be a text file like this:

Snowball???white???F???1???lazy


1.Get Started

Create  two functions to interact with the Cats database:  "initialize-cat-record.php' and 'read-cat-record.php'.

initialize-cat-record.php

This code creates an empty associative array called '$catrecord' with labels as indexes: 

$catrecord = array ('name' =>'', 'color' => '', 'sex' => '', 'age' =>'', 'extra' => '');

initialize-cats-record.php

read-cat-record.php

This code reads the text record for a particular cat using the provided '$catid'.   Snowball's record would be here:  'cats/showball.txt'

This text file is exploded and each field saved in the new empty array, '$catrecord;

$catrecord = array ('name' => 'Snowball', 'color' => 'white', 'sex'=> 'F", 'age' => '1', 'extra' => 'lazy')

read-cats-record.php

2.  Display the table

The code to display the table is found in 'index.php'.  First, a header is set up with each of the labels:  Id, Name, Color, Sex, Age, and Extra.   The Id is a link to the editing page.

The table is created by a loop that reads each text file inside the 'cats' folder and displays the items from that record in the appropriate columns.

index.php

index.php


3.  Add and Update Records in Table


add or update screen


 

add-update-cat-record.php

The 'add-update-cat-record.php' file displays the form and processes the submitted data.  The input field names are the same as the cat record labels, so the input data is automatically assigned to the approriate field in the cat record.

add-update 1add-update2

Category: code

Leave a Comment
Email  
Name   
Subject  
Message: