Putting form data into files with PHP

This page is marked as In Progress so expect small errors or unfinished bits

Although PHP is normally used with MySQL it can also store and retrieve data from text files on the server.

Storing new data in a file.

Create an HTML form with three text input elements and a submit button. The file should be formfiles.php and the action will be the same. The three form input fields will be called fruit, price and country. Remember the labels.

Place the form in an IF/ELSE statement so that it is only shown if not previously submitted.

In the other part of the IF/ELSE use print_r to show the contents of the $_POST variable. Test the form by entering data and submitting it. The print_r should show something like:

Array ( ["fruit"] => apple ["price"] => 45 ["country"] => UK )
        

Now delete the print_r line and put code in it's place. The code should:

Once you have that code test it and see if the file now has some data in it. Try it a second time to make sure the added data goes on a new line.

Reading data from a file into a table

Now that your text file has some data you can read it back out and display it nicely in a table.

When splitting the data be careful to split on tab or another special character and not space as the data could have spaces in it.

Save it and upload it to where the text file is. When loaded in a browser you should see each line of the file in a new paragraph. This is just to test it worked so far.

Once you know this is working replace the PRINT_R with ECHO. ECHO each part of $linearray with P tags as well. You may want to add some extra text (even if it is just a few spaces).

Now create a table for the data to appear in. That means creating the TABLE element and then (inside the loop) echoing TR tags instead of the P tags. Finally, put TD tags around each item of data. You may want to use a few ECHO lines or one with concatenation of the tags and variables.

If you examine the data carefully you will probably find that some of the data has an extra space at the end of it. This is because of the way special characters work in the form and PHP. TRIM can be used to remove them. This would be essential if you were doing any IF statements using the data.

Add more data to the text file and play with CSS to make the results look better.

submit to reddit Delicious Tweet