使用PHP将HTML表单输入写入csv文件
我有一个PHP表单,用户在其中输入数据。提交时,它应该打开一个现有的CSV文件并附加一些数据。我尝试了很多方法,但以下是我目前正在使用的最新代码: HTML:使用PHP将HTML表单输入写入csv文件,php,html,forms,csv,web-applications,Php,Html,Forms,Csv,Web Applications,我有一个PHP表单,用户在其中输入数据。提交时,它应该打开一个现有的CSV文件并附加一些数据。我尝试了很多方法,但以下是我目前正在使用的最新代码: HTML: <html> <head><title>Design Request</title></head> <title>Design Request</title> <form action="test2.php" method="POST
<html>
<head><title>Design Request</title></head>
<title>Design Request</title>
<form action="test2.php" method="POST">
<fieldset align="left">
<legend>Executive Sponsor Form</legend>
<p><i>To be completed by the executive sponsor</i></p>
<table>
<tr>
<td>Name:</td><td><input type="text" name="SPONSOR_NAME" size="40" /></td>
</tr>
<tr>
<td>Position:</td><td><input type="text" name="SPONSOR_POSITION" size="40" /></td>
</tr>
<tr>
<td>Telephone Number:</td><td><input type="text" name="SPONSOR_TELEPHONE_NUMBER" size="40" maxlength="11" /></td>
</tr>
<tr>
<td>Email Address:</td><td><input type="email" name="SPONSOR_EMAIL" size="40" /></td>
</tr>
<tr>
<td>Budget :</td><td><input type="checkbox" /><input type="text" name="BUDGET" size="37" maxlength="6" placeholder="budget code" /></td>
</tr>
<tr>
<td>Aligned to which<br> priority:</td><td><input type="text" name="PRIORITIES" size="40" /></td>
</tr>
<tr>
<td> Benefit to Business:</td><td><textarea cols="42" rows="10" name="BENEFIT"></textarea></td>
</tr>
</form>
<input type="submit" value="Submit">
设计要求
设计要求
执行发起人表格
由执行发起人填写
姓名:
职位:
电话号码:
电邮地址:
预算:
与哪个优先级对齐:
商业利益:
PHP:
<html>
<head>
<title>Your (Ref No: ["SPONSOR_NAME"]) has been submitted.</title>
</head>
<?php
$data = array("" . ',' . "SPONSOR_NAME" . ',' . "" . ',' . "" . ',' . "SPONSOR_EMAIL" . ',' . "PRIORITIES" . );
$cr;
$fp = fopen("/var/www/testdb.csv","w");
foreach ($data as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
?>
</html>
您的(参考号:[“赞助商名称”])已提交。
有些字段输入到一个工作表中,有些字段输入到另一个工作表中,这就是为什么我的数组中有一些空字段(我希望数据在B、E和F列中),其他列将包含来自另一个表单的数据。因为您已经为数据构建了数组,您可以使用PHP函数将该行写入文件
如果需要在其他表单的数据中填充这些空白,则必须重新打开文件,提取最后一行数据,将其分解为数组,填充缺少的数据,然后覆盖csv中的原始行。。。我不建议这样做,因为不同的用户可以提交表单的第一部分,然后将他们的新数据附加到csv的错误行中。。。在这种情况下,你真的应该听从@symcbean的建议,使用一个合适的数据库。让约翰振作起来,使用一个合适的数据库!它是Excel中现有的一个,我不能像这样:打开文件,表格1转到b列(发布数据)转到e列(发布数据)转到f列(发布数据)。然后表格2转到a列(发布数据)转到c列(发布数据)等等?PHP不会将CSV文件中的数据视为有列。每次要写入多维数组时,必须解析CSV数据,将新数据写入数组,然后将数组重新保存到CSV。这对于一个小型应用程序来说并不坏,但在规模上会有性能问题以及并发进程相互覆盖的问题read数据库可以优雅而轻松地处理这些问题。
$data = array("" . ',' . "SPONSOR_NAME" . ',' . "" . ',' . "" . ',' . "SPONSOR_EMAIL" . ',' . "PRIORITIES" . );
$file = "/var/www/testdb.csv"; //file to append to
$current = file_get_contents($file); //open the file
$current .= "\n" . implode(",",$data); //add line-break then comma separated array data
file_put_contents($file, $current); //append new content to file