create your own

PHP form inserts data into CSV file

81
rate or flag this page

By Alpho011

Reference Materials

Excel 2007 For Dummies (For Dummies (Computer/Tech)) Excel 2007 For Dummies (For Dummies (Computer/Tech))
Price: $12.17
List Price: $21.99
Microsoft Office Excel 2007 Microsoft Office Excel 2007
Price: $158.59
List Price: $229.95
Microsoft Office Excel 2007 Version Upgrade Microsoft Office Excel 2007 Version Upgrade
Price: $78.29
List Price: $109.95
Build Your Own Database Driven Website Using PHP & MySQL Build Your Own Database Driven Website Using PHP & MySQL
Price: $18.99
List Price: $39.95

Today we are going to use a .csv (comma seperated values) file to store values from a online PHP web form.

A csv file is file that you can create easily with Microsoft Excel, here are the full and upgrade versions, also you can also get knowledge from this recommended book on excel for further knowledge that is beyond the scope of this tutorial.

Ok first off we will use the multi-purpose page technique from Build Database Driven Website Using PHP and MySql.

We aren't using a database, we are going to use Excel in .csv form to store the form data.

Why do this when you can use a database:

  1. Data is portable
  2. Data is readily readable by MS office
  3. Data is web ready
  4. Web hosting is simple, FTP and done.

Before we start the files can be found here.

First we create a simple form:

<form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
<table class="formatTblClass">
<tr>
<th colspan="6"><?=$message;?></th>
</tr>
<tr>
<td width="68"><span>First Name</span></td>
<td width="215"><input class="<?=$aClass;?>" type="text" name="fn" id="fn" /></td>
<td width="62"><span>Last Name</span></td>
<td colspan="3"><input class="<?=$aClass;?>" name="ln" type="text" id="ln" size="50" /></td>
</tr>
<tr>
<td colspan="6"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="71">Address</td>
<td width="721"><input class="<?=$aClass;?>" name="address" type="text" id="address" size="100" /></td>
</tr>
</table></td>
</tr>
<tr>
<td><span>City</span></td>
<td><input class="<?=$aClass;?>" type="text" name="city" id="city" /></td>
<td><span>State</span></td>
<td width="148"><input class="<?=$aClass;?>" type="text" name="state" id="state" /></td>
<td width="24"><span>ZIP</span></td>
<td width="255"><input class="<?=$aClass;?>" type="text" name="zip" id="zip" /></td>
</tr>
<tr>
<td><span>Phone</span></td>
<td><input class="<?=$aClass;?>" type="text" name="phone" id="phone" /></td>
<td><span>Email</span></td>
<td><input class="<?=$aClass;?>" type="text" name="email" id="email" /></td>
<td><input name="emailMe" type="checkbox" id="emailMe" value="Yes" checked="checked" /></td>
<td>Please send me email</td>
</tr>
<tr>
<td colspan="6"><span>Comments
<textarea name="comments" id="comments" cols="45" rows="5"></textarea>
</span>
<div align="center">
<input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="reset" name="Reset" id="button" value="Reset" />
</div></td>
</tr>
</table>
</form>

Same deal, simple form, great results, you can use this technique using any type of form you want, even then one from my other article.

Then we need to create a csv file;

Excel and for this particular one we created the following headers:

First Name
Last Name
Address
City
State
ZIP
Phone
Email
Yes/No
Comments

Those will go across the first row and will match our variables in our PHP script to insert them into the sheet.

After clicking the submit button we want to do some checks:

$fn = $_POST['fn'];
$ln = $_POST['ln'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$emailMe = (isset($_POST['emailMe'])) ? $_POST['emailMe'] : 'No';
$comments = $_POST['comments'];

//validate

if(empty($fn) || empty($ln) || empty($address) || empty($city) || empty($state) || empty($zip) || empty($phone) || empty($email)){//show the form
$message = 'Fill in areas in red!';
$aClass = 'errorClass';

In this case we show the form again, somebody may have miss some things we find important.

If all is good we get to the good stuff the insert:

First we tie all the data up in a variable called $csvData:

//this is where the creating of the csv takes place
$cvsData = $fn . "," . $ln . "," . $address . "," . $city . "," . $state . "," . $zip . "," . $phone . "," . $email . "," .$emailMe . "," . $comments ."\n";

then we open the file:

$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to file $filename

And then we write the form contents to the file:

if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file

And close the connection or file.

Simple, once again look over the source files and get a feel for doing this, these techniques can be used in conjuction with email, storing in db and storing this in a regular text file, the limit is your imagination.

Please be sure to leave any questions or comments you may have about this, and enjoy your projects.



Print   —   Rate it:  up  down  flag this hub

Comments

RSS for comments on this Hub

Lgali profile image

Lgali  says:
8 months ago

thanks for this info

Alpho011 profile image

Alpho011  says:
8 months ago

Thanks and I hope this proves helpful!

exor  says:
8 months ago

thank you so much! my php and scripting skills are very much copy-and-paste-and-hack-and-trial-and-error and for hours now i've been trying to find a way to do a simple club guestlist sign-up form for a friend and i've managed to hack your sample enough to make it work for this purpose.

such simple guestlist scripts are quite literally impossible to find... not on hotscripts, not anywhere. (i guess it's become most programmers can whip up something like this in 5 minutes)

once again, thanks and i'm bookmariking this for when you post something else this useful.

Alpho011 profile image

Alpho011  says:
8 months ago

Well I appreciate that, and I am very pleased it worked for you!

al  says:
7 months ago

what happens if someone enters a comma into the input field?

Alpho011 profile image

Alpho011  says:
7 months ago

Well I did it and it still inserted, but the real problem will more than likely come when we present the data (loop it out).

we should check for any bad things (validate and clean).

$badThings = array(" , " );

Look through the posted values and stop the insert.

Thanks for the comments.

JYOTI KOTHARI profile image

JYOTI KOTHARI  says:
7 months ago

Hi Alpho011,

Technical things described easy. Now we can make our own CSV files.

Thanks.

Jyoti Kothari

http://business-club.ning.com

payam  says:
7 months ago

hi.

i downloade the file and run it but it dosen't work .

when i press submit button then i got this error message:"The file /C:/New Folder (2)/<?=$_SERVER['PHP_SELF'];?> cannot be found. Please check the location and try again."

could you please help me??

jared Schott  says:
7 months ago

Brilliant and Beautiful! So easy and an inexpensive option to filemaker pro database hosting. But easy to import into our clients FMPro datbases.

The email checkbox is not initiating an email for some reason though.

do you have a gui editor that you recommend for adding new forms or adding a header or logo? Would frontpage work?

Great Job,

Respectfully,

Jared

www.developerranch.com

Alpho011 profile image

Alpho011  says:
7 months ago

Happy Easter payam :

from the look of the error "do you have PHP installed?"

The PHP_SELF should read the name of file, in other words it submits on itself.

Alpho011 profile image

Alpho011  says:
7 months ago

Happy Easter jared Schott:

I always use Dreamweaver in code view but you can edit in any editor to include Notepad, straight html and php, the GUI based editors have a syntax editor which are really good in helping and syntax coloring.

And thank you for the comment.

Chris  says:
7 months ago

"what happens if someone enters a comma into the input field?"

The safest way to create a CSV file is to have each value bounded by a double quote so that the data looks like this:

"field 1","field 2","field 3","etc"

There should be no space between the quotes and commas. By doing this it is safe to have commas in a field and usually safe to have new line breaks in the field as well.

Escape a double quote in the field value with another double quote i.e. ""

Brady Vitrano  says:
7 months ago

I would much rather save my field values into an array and then implode the data.

$csvArray = array($fn, $ln, $address, $city, $state, $zip); $csvData = '"'.implode('","', $csv_values).'"'.PHP_EOL;

This allows for easy edits. For example to reorganize the fields.

$csvArray = array($address, $city , $state, $zip, $ln, $fn); $csvData = '"'.implode('","', $csv_values).'"'.PHP_EOL;

Just my two cents.

Clareen  says:
7 months ago

After fill in all the information and submit, it shows "Error saving file! Fill in areas in red!". Please help

Alpho011 profile image

Alpho011  says:
7 months ago

Clareen: Are the permissions on the CSV file set to 755 or 777, that is what is sounds like, you can use and FTP program to set the file settings, by right clicking on the folder and setting the read,write settings.

Kudlit profile image

Kudlit  says:
6 months ago

Hey I've been wondering what CSV means but was too lazy to Google it. Now I know. Thanks!

JimmyBBB  says:
6 months ago

Thanks so much for posting this tutorial, I can't believe how easy it was to implement this script!

One (or more) question(s)... If the check fails and the form is redisplayed with the red outlines, all of the previously entered data is removed and the user must start over.

1. What maintains the user entered data between submits?

2. What would I need to look at in order to maintain this information with the script you have already provided?

Thanks again,

Jimmy

Sam  says:
6 months ago

after I fill in all the fields I get the following error

The website declined to show this webpage HTTP 403 Most likely causes:This website requires you to log in.

Operating System: 2003 Standard Edition SP2Webserver: Apache 2.2.6PHP: 5.2.4

Alpho011 profile image

Alpho011  says:
6 months ago

You are more than likely recieving this because the directory listings are turned off on Apache.

Bhushan  says:
5 months ago

u create the string from input date , but in that if , is come in the address field then what happend it insert it into new cell not in same cell of address field.

Michael  says:
5 months ago

Hi Alpho011,

I seem to be having problems with the permissions. after i click submit this error happens on top of the page.

Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in C:\www\contactFrm.php on line 215

Btw. Im using IIS on windows xp pro . and php 5.29-2

thanks so much

Michael  says:
5 months ago

Hi Alpho011,

I seem to be having problems with the permissions. after i click submit this error happens on top of the page.

Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in C:\www\contactFrm.php on line 215

Btw. Im using IIS on windows xp pro . and php 5.29-2

thanks so much

Alpho011 profile image

Alpho011  says:
5 months ago

Been out in Miami, so I apologize:

The folder permissions have to be set at 755 (chmod)

Jarrod  says:
3 months ago

Thanks for this tutorial. You mention applying this to email, which is exactly what I need to do. I'd like to have form data go into a csv and then have that csv emailed to a recipient. Can someone help? Thanks.

Dan  says:
3 months ago

Hi Alpho011. I placed the csv file on the server and created a php file with the recommended codes. However, when I filled out the form and clicked on Submit, the entries were gone but I didn't see the 'Successfully Saved' message, and of course there was no entry into the csv file.

Also when I tested leaving out some fields and clicked on Submit, I did not get the error message in the code. However, I have php 5.11 installed on the computer and all the php forms for another website work well. Do you have any idea what had gone wrong on my side?

Thanks!!

Nie  says:
2 months ago

Hi,

Thanks a lot...This one really worked for me:)

Ilikeautumn  says:
2 months ago

thanks so much. It's work (IIS 5.1, php 5.1.1)

Matt Yates  says:
6 weeks ago

How can i redirect to a new page upon successful form submission? thanks!

johnta1  says:
3 weeks ago

Brady, do you have any more info on your array idea?

Would the array would with a big array, like 30 items or so?

Sounds like something I would like to do.

Thanks.

Submit a Comment

Members and Guests

Sign in or sign up and post using a hubpages account.


optional


  • No HTML is allowed in comments, but URLs will be hyperlinked
  • Comments are not for promoting your hubs or other sites

working