Simple Flat-File Database

2019-01-08

Do you need a simple way to manage a small amount of data on your website? The following example shows an application that uses a single table in a flat file database:

Simple  flat file database application

figure 1

Advantages

 A flat-file database can be created, modified and moved quickly and easily.  Since all the records are text files, all data types are defined as 'text' and initialized to empty.   You only need to choose field names to create a table, and the data can be managed using basic PHP statements.

Functions to create, read, update and remove records are provided, using the following folders and files:

files in all-my-cats application

Files in the 'inc' folder:

files in the all-my-cats inc folder

Records in the 'cats' table are represented by character-delimited text files.

data files used for the all-my-cats application

Contents of 'snowball.txt':

Snowball***white***F***1***Has PhD in Lazy

Output from the 'index.php' file (figure 1) lists all current records in the database. 

Necessary Functions

There are 6 necessary functions for each table in this flat-file database:   'define', 'read', 'display', 'create/update', 'create-id' and 'remove'. 

Let's look at each of these functions:

1) 'define' creates an empty array of labels for the table fields.  

define-cat-table.php

<?php
 $catfields = array ("Name", "Color", "Sex", "Age", "Details"); 
?>

2) 'read' creates an associative array, $catrecord,  with labels as keys and text file data as values

  read-cat-record.php

<?php
  
include ("define-cat-table.php");

//CREATE AN EMPTY ASSOCIATIVE ARRAY 
$catrecord = array();
foreach ($catfields as $label) {
   $catrecord[$label] = ""; 
}

//READ SELECTED  RECORD AND ASSIGN VALUES TO ASSOCIATIVE ARRAY
$catstring = "";

if (file_exists ("data/cats/" . $catid . ".txt") ){
    $catstring = file_get_contents ("data/cats/" . $catid . ".txt");     
                   
    if ($catstring !== "") {
        $catarray = explode ($delim1, $catstring);

        foreach ($catfields as $pos => $label) {               
            if (array_key_exists ($pos, $catarray)) {

                //FILL ASSOC ARRAY WITH DATA FROM FILE
                $catrecord [$label] = trim ($catarray[$pos]);             
            }
        }
    }
}


?>

3) 'display' - does just that. However, you could also list each field individually. 

display-cat-record.php:


<?php
//DISPLAY LABELS AND VALUES FOR THIS RECORD
echo "<b>Id: </b>" . $catid . "<br><br>";
foreach ($catrecord as $label => $field) {   
        echo "<b>" . $label . "</b>:&nbsp;&nbsp;" .   $field . "<br><br>";            
}
?>   

4) 'create/update' - create-update-cat.php:

First, a form is presented.

<form method='post' action='create-update-cat.php?catid=<?php echo $catid ;?>'> 
         
    <?php
    echo "<b>Id: </b>" . $catid . "<br><br>";
    foreach ($catrecord as $label => $field) {    

        echo "<b>" . $label . "</b> " ;
        echo "<input name = '" . $label . "' type = 'text' value = '" .  $field . "'><br>";            
        }
    ?>                          
    <br>
    <input class = 'adminbutton' type = 'submit' name = 'submit' value='Update'/>         
</form> 

Then, the form input is read and replaces the data in the original record array.

<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST" ) {     
    
    //ASSIGN FORM DATA TO RECORD 
    foreach ($catfields as $field) {      
       if (isset ($_POST[$field])) {            
           $catrecord [$field] =  trim($_POST[$field]);             
       }
    }
}

Finally,  the updated record is converted to a string and written to the file.  If this is a new record, an appropriate record id is created first.

<?php
//RETRIEVE FORM INPUT 
if ($_SERVER ["REQUEST_METHOD"] == "POST" ) {     
    
    //ASSIGN FORM DATA TO RECORD 
    foreach ($catfields as $field) {      
       if (isset ($_POST[$field])) {            
           $catrecord [$field] =  trim($_POST[$field]);             
       }
    }

    //CREATE A RECORD ID IF NONE EXISTS
    $error = false;  
    if ($catid === '') {
        $table = 'cats';
        $namestring = $catrecord['Name'];
        include ("inc/create-record-id.php");
        $catid = $newid;
    }
   
    //UPDATE RECORD
    if ($error === false) {         
        $catstring = implode ($delim1, $catrecord);
        $catstring = html_entity_decode ($catstring, ENT_QUOTES );
        file_put_contents ("data/cats/" . $catid . ".txt", $catstring);  
    } 
    
 }

?>

5) 'create id' creates a unique key for a record.  This code can be used for multiple tables.

create-record-id.php

<?php

//CAN BE USED WITH ANY TABLE
 $newid = ""; 
 if ($namestring === '') {
     echo "<div class = 'error'>Missing  Name</div>";  
     $error = true;
     
 }
 else {
    $newid  = str_replace(" ", "-", $namestring);  
    $newid = strtolower ($newid);
    $newid = preg_replace('/[^\A-Za-z0-9-]+/', '', $newid); 
    if ($newid === "") {
         echo "<div class = 'error'>Invalid Record Name</div>";  
         $error = true;       
    }    
    else {  
        
        // CHECK THAT THIS RECORD DOESN'T ALREADY EXIST   
        $filename = "data/cats/" . $table . "/" . $newid . ".txt";  
        if (file_exists ($filename)) {
           echo "<div class = 'error'>record with this name already exists</div>"; 
           $error = true;   
           //set newid to empty
           $newid = "";
        }        
    }
 }

 
?>

6) 'delete' -  a form is presented asking if you are sure you want to delete the record:

remove-cat.php

<form method = 'post' action = 'remove-cat.php?catid=<?php echo $catid; ?>'>
    <h3>Are you sure you want to remove <?php echo $catrecord['Name']; ?>?</h3><br>
     NO <input class = 'radio-input' type = 'radio' name = 'removeflag' value = '' checked /> <br>        
     YES <input class = 'radio-input' type = 'radio' name = 'removeflag' value = 'REMOVE' />  
    <br><br><input class = 'adminbutton' type = 'submit' name = 'submit' value='Remove'/>
</form>  

If the form shows a 'yes', the file is moved to the 'removed' folder

<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST" ) {   
   if (isset($_POST ['removeflag'])) {
      $removeflag = trim($_POST['removeflag']);
      if ($removeflag === "REMOVE") {

          if (file_exists ("data/cats/" . $catid . ".txt")) {
              rename ("data/cats/" . $catid . ".txt", "data/cats/removed/" . $catid . ".txt");  
          }        
      }
   }
}

?>

 


 

These six basic functions have been embedded into web pages and styled in the downloadable code for this application. 

Download  'All My Cats'

View the demo (write functions have been disabled)

 

 

 


To post a comment Login or Register