Simple Flat-File Database Tutorial Using PHP
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:
Files and folders we will need to manage our Cats database:
After we have added some records the contents of the 'cats' folder will look like this:
The record for 'Snowball' in 'cats/showball.txt' will be a text file like this:
Create two functions to interact with the Cats database: "initialize-cat-record.php' and 'read-cat-record.php'.
This code creates an empty associative array called '$catrecord' with labels as indexes:
$catrecord = array ('name' =>'', 'color' => '', 'sex' => '', 'age' =>'', 'extra' => '');
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')
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.
3. Add and Update Records in Table
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.