2014-08-28 148 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 ; 
相關問題