Syndicate content
> HOW-TO: PHP & Flat File Databases : PHP Tutorials

HOW-TO: PHP & Flat File Databases : PHP Tutorials

PHP Tutorials


PHP Tutorials
Probably one of the oldest form of database, a text-file (flat0file) database can be quick and easy. It is also not very flewxible and will not scale easily with a large web application or site. If you need to run alot of dynamic queries, perhaps this kind of database is not for you. Let's take the instance of the following form variables being submitted to subscribe to a e-newsletter. The variables are $lastname,$firstname,$email,$format,$date.

First we'd have the form data submitted to a processing page. Let's call it process.php. process.php is going to write to email.csv which will be accessed later as a CSV file.

What is a CSV file? CSV means Comma Separated Value. Each database "field" is separated by a comma. You could use a semicolon or any other "always used, only for this purpose" character. I will end each line with a break so each database record is on its own line:

First we get all the variables out of the $_POST array, since they were all submitted by a form that used the POST method. I use the @ to suppress errors in case the form was submitted with NO values in the $_POST array which would result in a parse error.


@extract($_POST);

First we need to make sure the file is able to be written to. Enter is_writable().:


if(is_writable('emails.csv'))
{

Now we need to OPEN the file for writing. For this we use fopen(). We also use the a attribute to make sure we "append" to the end of the file


$fp = fopen('emails.csv','a');

Now we want to write the data. We use fwrite().


$content = "$lastname,$firstname,$email,$format,$date\n";
fwrite($fp,$content);

Now we close the connection to the CSV file:


fclose($fp);
}

Finally, if the file wasn't writable above, we'll send this output to the browser:


else
{
echo'File is not writable';
}

That's it.

Here's the code as a whole:


<?php
@extract($_POST);
if(is_writable('emails.csv'))
{
$fp = fopen('emails.csv','a');
$content = "$lastname,$firstname,$email,$format,$date\n";
fwrite($fp,$content);
fclose($fp);
}
else
{
echo'File is not writable';
}
?>

That's it!
Aaron Brazell
www.emmense.comAaron owns and operates Emmense Technologies, a Web development company geared toward non-profit clients. He is also Partner and System Admin for .
Barefooting.com Web Hosting Services

User login

Christian-Web-Masters.com newsletter

Stay informed on our latest news!