PHP form inserts data into CSV file
81Reference Materials
|
Excel 2007 For Dummies (For Dummies (Computer/Tech))
Price: $12.17
List Price: $21.99 |
|
Microsoft Office Excel 2007
Price: $158.59
List Price: $229.95 |
|
Microsoft Office Excel 2007 Version Upgrade
Price: $78.29
List Price: $109.95 |
|
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:
- Data is portable
- Data is readily readable by MS office
- Data is web ready
- 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.
PrintShare it! — Rate it: up down flag this hub
Comments
Thanks and I hope this proves helpful!
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.
Well I appreciate that, and I am very pleased it worked for you!
what happens if someone enters a comma into the input field?
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.
Hi Alpho011,
Technical things described easy. Now we can make our own CSV files.
Thanks.
Jyoti Kothari
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??
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
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.
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.
"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. ""
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.
After fill in all the information and submit, it shows "Error saving file! Fill in areas in red!". Please help
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.
Hey I've been wondering what CSV means but was too lazy to Google it. Now I know. Thanks!
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
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
You are more than likely recieving this because the directory listings are turned off on Apache.
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.
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
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
Been out in Miami, so I apologize:
The folder permissions have to be set at 755 (chmod)
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.
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!!
Hi,
Thanks a lot...This one really worked for me:)
thanks so much. It's work (IIS 5.1, php 5.1.1)
How can i redirect to a new page upon successful form submission? thanks!
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.











Lgali says:
8 months ago
thanks for this info