PHP form inserts data into CSV file

83
rate or flag this page
Facebook

By Alpho011

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.

Since my server location is offline, email me for the src code, sorry.

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.



Reference Materials

Excel 2007 For Dummies
Amazon Price: $12.48
List Price: $21.99
Microsoft Office Excel 2007 [Old Version]
Amazon Price: $87.00
List Price: $229.95
Microsoft Office Excel 2007 Version Upgrade [Old Version]
Amazon Price: $114.99
List Price: $109.95
Build Your Own Database Driven Website Using PHP and MySQL
Amazon Price: $12.94
List Price: $39.95

Comments

Lgali profile image

Lgali 2 years ago

thanks for this info

Alpho011 profile image

Alpho011 Hub Author 2 years ago

Thanks and I hope this proves helpful!

exor 2 years 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 Hub Author 2 years ago

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

al 2 years ago

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

Alpho011 profile image

Alpho011 Hub Author 2 years 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 Level 2 Commenter 2 years ago

Hi Alpho011,

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

Thanks.

Jyoti Kothari

http://business-club.ning.com

payam 2 years 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 2 years 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 Hub Author 2 years 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 Hub Author 2 years 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 2 years 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 2 years 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 2 years 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 Hub Author 2 years 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 2 years ago

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

JimmyBBB 2 years 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 2 years 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 Hub Author 2 years ago

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

Bhushan 2 years 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 2 years 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 2 years 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 Hub Author 2 years ago

Been out in Miami, so I apologize:

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

Jarrod 2 years 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 2 years 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 2 years ago

Hi,

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

Ilikeautumn 2 years ago

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

Matt Yates 2 years ago

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

johnta1 2 years 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.

paul 2 years ago

Warning: fopen(formTest.csv) [function.fopen]: failed to open stream: Permission denied in /public/html/pdinardo/formtocsv/contactFrm.php on line 215

Any help would be appreciated.

pravin 2 years ago

play with php

pravin 2 years ago

play with php www.mahaphpcode.com

Brady Vitrano 2 years ago

Hi Johnta1,

Sorry it has been a couple months since I checked this posting. Any size array will work.

samir 23 months ago

Not Run on Browser Server. Proper run on Localhost.

bry 23 months ago

in your smaple code download you have five forms and its very hard to remove them so i can work with it using my bare bones php skills ... help

Claire 23 months ago

I am getting an error message and can't seem to fix it, any ideas?

Steve 23 months ago

I seem to be getting a similar error to a poster on this thread (payam). I get an error that appears to be a response to the tag. My error reads No file exists at the address “/Users/steve/Desktop/csvCreate/

Steve 23 months ago

Sorry, the tag I was referring to didn't show up in my post. I'm referring to the php tag that calls itself "". My error reads No file exists at the address “/Users/steve/Desktop/csvCreate/

Rohini 22 months ago

when we download the csv file it is in readonly format, how to edit the values without using saveas

Roberto Certain 22 months ago

Hi, I need someone to build insert this to my website. I can pay with paypal. My email is robertoandrescertain@hotmail.com

Andrew 22 months ago

Good day - Thank you very much for this. 1 small problem though, I have added a field, credit card number, (also cvv, expiration date, and amount) (using this as a very basic shopping cart) and all the fields work great, except that the last digit of the credit card number is chopped off, and replaced with a 0. I have looked and dug, but unable to find anything that is limiting the numbers to 15 digits. makes no difference in IE, or Firefox. Any suggestions. skyegod@gmail.com

Thanks

Andrew

jim10 profile image

jim10 21 months ago

I need to make a form on a site that asks who a person is and whether they are attending 1 or 2 of multiple events. It looks like this would work great. I'm just wondering if the .csv gets updated by each user that submits the form or if it makes multiple pages.

Thanks,

Jim

Alpho011 profile image

Alpho011 Hub Author 21 months ago

@jim10,

It updates the csv!

gorgeous19 20 months ago

wow!!! really worked! a million thanks! it's really brilliant.. :)

Alpho011 profile image

Alpho011 Hub Author 20 months ago

De nada

Shahid Ali 20 months ago

if any one need code for php pay $50

UTAN 20 months ago

Thanks for this great script... I have a question...

My form pass 8 $variables and it writes fine, the first part after writing to the file is the date, that you entered in the form, what I want is to read the file and put it in tables and also have a little search form that the user will enter the date and when submitted, the script look into the file written the find the date entered and show all the complete line where the user submitted before.... can you help find the write direction? hope I make sense... regards

Alpho011 profile image

Alpho011 Hub Author 20 months ago

@UTAN

//maybe this

$file = fopen("test.csv", "r") or exit("Unable to open file!");

while(!feof($file)){

if($test == $dateRange){

echo fgets($file). "";

}

}

fclose($file);

Don't know if that will work, but it makes sense for the moment.

Balaji J H 19 months ago

Hi,

Its really worked!!!

Thanks

Balaji J H 19 months ago

Hi,

It Really Word!

Thanks a ton :)

Richard 19 months ago

Hi Alpho011, i have never used PHP before and im confused on what to do after i have put the varibles in to the CSV file?

Can anybody help

Shakeeb 18 months ago

Hi,

I copied your code and tried it. When I submit the button the page got refresh but didn't created the csv file. We should manually create the csv file or this code will create the file.

Thanks.

Trilby 18 months ago

Thank you! I wish I had found this earlier. I created a Certificate Request form for an online class which gets mailed to me. Your form will cut my workload way down and should prevent any errors in transposing.

One question before I get started. I am confused about the session_start section. I have never put anything above a doc type declaration. Is that really where it goes? Thanks again!

shafeer 18 months ago

I felt problem when I create a doc file. That created of 100% width,but I want the doc of 80% width.

I hope you can help me....

the code given below

$page_content = ''.$gls_cat_name.''.$term_content.'';

header("Content-type: application/vnd.ms-word");

header("Content-Disposition: attachment;Filename=".$file_name.".doc");

echo ''.''.$ps_title.''.$page_content.'';

Crysoft 18 months ago

just a suggestion but for all you guys who want to avoid errors, how about pluggin in a javascript validation like the JQuery Validation plugin ( http://docs.jquery.com/Plugins/Validation ) or Real Simple Validation (http://www.benjaminkeen.com/software/rsv/) You simple include them in your page and set the value as required and it will do the rest. You don't even have to know Javascript to do it.

Just a thought.

Alpho011 profile image

Alpho011 Hub Author 18 months ago

@Trilby:

The session start is needed if your using a session on the page for anything.

It should always go at the top if used.

Richard 18 months ago

i m having acturally trying to look at what has been done and whenever i true to view it on IE8 im asked to eiether download the PHP or save it. Is this because you need to have a domain to view thw PHP or is there something else?

Richard

nicha 17 months ago

thanks for this info

Alpho011 profile image

Alpho011 Hub Author 17 months ago

@Richard: Yes you need a way to host the PHP script.

jasdeep 17 months ago

Hi

Important question

What if someone enters "," comma in comments field, it will shift it to new cell in csv, is'nt that?

So how to avoid that condition?

ahmad 15 months ago

hello iam ahmad from syria look that code is really useful and iwant try this right now but i thinks its easy to hack yes its

Pete 15 months ago

Thanks Alpho, great finding this little nugget of code. Has really helped me with my little Newsletter sign-up feature.

Pete 15 months ago

Actually, for some strange the server errors when I submit the form unless I remove the line: if($fp){

With this line removed everything works fine, so I'm still happy :-)

Darren 15 months ago

The files don't appear to be hosted anymore - does anyone have a copy please?

Cheeers Darren

Imran110 13 months ago

Hi, I am new on PHP so i don't know how to use this script in form? Can you please help me that how i can use this script in PHP Format?

weberry 13 months ago

Hi,

Can you please post the files. They don't appear when I press the blue link.

Thank You

aero 12 months ago

its not work its aall wasted.

aero 12 months ago

its not work its aall wasted.

Xten 11 months ago

im sorry, im a PHP beginner, i found error,

Parse error: syntax error, unexpected $end in C:\xampp\htdocs\sample\sample2.php on line 82

what will i do?

Alpho011 profile image

Alpho011 Hub Author 11 months ago

Xten

You are missing a bracket in your php or mine, I am sorry everyone the src files are not not online I took down the hosting looking for a new method.

Xten 11 months ago

how about this error?

Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.

Error 403

localhost

3/9/2011 9:51:31 AM

Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1

Anon 11 months ago

So will you be putting up the source files somewhere?

I have looked everywhere and this is exactly what I need.

Thanks

CR 10 months ago

Is creating the CSV file as simple as writing out the list of field names like the example at the top of this page?

Rohan 10 months ago

Thanks - works a treat...although validation wasn't working straight off the bat. Will have a play!

kearney 8 months ago

would love to have a look at the source files. hope you can post them soon.

amritags 8 months ago

great work.......i have tried it and it works

But i have a doubt....

In the comments field which is a text area,if two or more lines are typed with the enter key then it comes in the name field.Please specify a step to rectify this.I have a work related to this.

murf 5 months ago

I also would like to get the code, or if someone can tell me how to use what is in this tutorial my php is not great.

Thanks

Michael Redford 3 months ago

Im an amatuer and need the script for this but only want name and email

Can you send to me please

redford.michael@gmail.com

Pyari 2 months ago

Its really gud.

Jackie Barnsley 12 days ago

Hi I have followed your excelelnt description and got the form to work and export to a csv file, unfortunately I run into the same problem as a previous poster and if someone puts in a comma or a return, it messes it up in the excel. Also I need a field for other comments so sometimes this can be left blank, so i have left out the checks for empty. I am interetsed in the reponse to put the values in double quotations or the array idea but will need more information as to how to do that, please.

Michelle Lee 6 days ago

Thanks for the post. Here’s a tool that lets you build your custom web form in minutes – without coding. Just point-and-click

http://www.caspio.com/online-database/features/web

Submit a Comment
Members and Guests

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



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

    working