How to insert web form data into csv file using php
I am trying to get the data store in a csv file via a web form, I have tried below codes that are saved in "form.html", "form1.php", "formTest.csv" and all three are in the same directory.
<form id="form1" name="form1" method="post" action="form1.php">
<table class="formatTblClass">
<tr>
</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>
<div align="center">
<input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="reset" name="Reset" id="button" value="Reset" />
</div>
</table>
</form>
Now form1.PHP script
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
if(empty($fn) || empty($ln))
{//show the form
$message = 'Fill in areas in red!';
$aClass = 'errorClass';
}
$cvsData = $fn . "," . $ln . "\n";
$fp = fopen("formTest.csv","a");
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
?>
Now the formTest.csv file
If I run this in a browser and update the csv file again, I get the output as shown below.
How do I get the correct custom output?
thanks in advance
+3
source to share
3 answers
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
if(empty($fn) || empty($ln))
{
//show the form
$message = 'Fill in areas in red!';
$aClass = 'errorClass';
}
else
{
$fp = fopen('formTest.csv', 'w');
$cvsData = $fn . "," . $ln . "\n";
fputcsv($fp, $cvsData);//use fputscv()
fclose($fp);
}
?>
0
source to share
Try it.
<?php
if(isset($_POST['fn']))
{
$csv=array();// take an array
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$csv[]=$fn;
$csv[]=$ln; //push the values in an array.
if(empty($fn) || empty($ln))
{//show the form
$message = 'Fill in areas in red!';
$aClass = 'errorClass';
}
$fp = fopen("formTest.csv","a");
if($fp)
{
foreach ($csv as $val)
{
fputcsv($fp, $val); //write data in csv file.
}
fclose($fp); // Close the file
}
}
?>
0
source to share