2014-08-28 139 views
0

我试图将表单数据插入到csv文件,即逐行,但问题是一个接一个地追加数据,但数据插入到csv文件的同一行。将表单数据插入到csv文件中逐行php

这是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文件第一行不包括和第二次我插入数据追加在同一行。它显示在下面的快照中:pleas find。 enter image description here

附加新文件: 当我添加时,它不会更新:fwrite($ fp,$ cvsData。“\ n”); 请查看快照: enter image description here

+0

你可以看看'fputcsv':http://php.net/manual/en/function.fputcsv.php – Sugar 2014-08-28 10:38:26

回答

1

您错过了换行符。你想:

fwrite($fp,$cvsData."\n") 
+0

无法在新行 – John 2014-08-28 10:40:14

+0

中插入数据,它也显示警告消息:警告:fopen(formdata.csv)[function.fopen]:未能打开流:权限被拒绝C:\ PORTAL \ xampp \ htdocs \ get_insert_csv \ insert.php on line 13 – John 2014-08-28 10:40:58

+0

对不起,我的错误文件已经打开并且我正试图再次打开这就是为什么它显示错误。现在请告诉我第一行是排除为什么? – John 2014-08-28 10:45:03

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

+0

是的,我做到了,但第一行仅在新行中排除和插入数据 – John 2014-08-28 11:16:55

0

$cvsData添加\n

$cvsData = "\n" . $first . "," . $last . "," . $address ;