我试图将表单数据插入到csv文件中,即逐行插入,但问题是一个接一个地附加数据,但数据插入到csv文件的同一行。
这是HTML表单:
<!DOCTYPE>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form id="form1" name="form1" method="post" action="insert.php">
<table border=1>
<tr>
<td width="30"><span>First Name</span></td>
<td width="30"><input type="text" name="fn" id="fn" /></td>
</tr>
<tr>
<td width="30"><span>Last Name</span></td>
<td colspan="3"><input name="ln" type="text" id="ln" size="50" /></td>
</tr>
<tr>
<td width="71">Address</td>
<td width="10"><input class="" name="address" type="text" id="address" size="100" /></td>
</tr>
<tr><td></td>
<div align="center">
<td><input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="reset" name="Reset" id="button" value="Reset" />
</td>
</div>
</tr>
</table>
</form>
</body>
</html>
这是php程序:
<?php
$first=$_POST["fn"];
$last=$_POST["ln"];
$address=$_POST["address"];
echo "$first <br> $last <br> $address";
if(!empty($first) || !empty($last) || !empty($address)){
$cvsData = $first . "," . $last . "," . $address ;
$fp = fopen("formdata.csv","a"); // $fp is now the file pointer to file $filename
if($fp)
{
fwrite($fp,$cvsData)"; // Write information to the file
fclose($fp); // Close the file
}
}
?>
我第一次插入细节: abcd,efgh,ijkl 我第二次插入细节时: abcd,efgh,ijkl
问题出在csv文件中第一行排除,第二次我插入数据追加到同一行。如下图所示:请求发现。
附上新文件: 我添加时不会更新:fwrite($ fp,$ cvsData。“\ n”); 请找到快照:
答案 0 :(得分:1)
你错过了换行符。你想要:
fwrite($fp,$cvsData."\n")
答案 1 :(得分:0)
这对我有用:
if(!empty($first) || !empty($last) || !empty($address)){
$cvsData = $first . "," . $last . "," . $address . "\n"; // Add newline
$fp = fopen("formdata.csv","a"); // $fp is now the file pointer to file $filename
if($fp)
{
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
}
此外,您在fwrite($fp,$cvsData)"; // Write information to the file
应为fwrite($fp,$cvsData); // Write information to the file
答案 2 :(得分:0)
在\n
中添加$cvsData
:
$cvsData = "\n" . $first . "," . $last . "," . $address ;