簡體   English   中英

在php中逐行將表單數據插入到csv文件中

[英]Insert form data into the csv file line by line in php

我正在嘗試將表單數據插入到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”); 請找到快照: 在此處輸入圖片說明

您缺少換行符。 你要:

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

這為我工作:

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

應該是fwrite($fp,$cvsData); // Write information to the file fwrite($fp,$cvsData); // Write information to the file

$cvsData添加\\n

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM