我有一个写入csv文件的公司竞赛表格。每个家庭只有一个条目,所以在提交时我想检查提交的地址是否已经在写入之前输入到csv文件中。我已经看到你可以在哪里使用SELECT与数据库,但我不知道如何使用.csv
这是代码:
if($_POST['formSubmit'] == "Enter Now") {
$errorMessage = "";
$aClass = "";
if(empty($_POST['name'])){$errorMessage .= "<li>You forgot to enter your name!</li>";}
if(empty($_POST['email'])){$errorMessage .= "<li>You forgot to enter your email!</li>";}
if(empty($_POST['address1'])){$errorMessage .= "<li>You forgot to enter your address!</li>";}
if(empty($_POST['city'])){$errorMessage .= "<li>You forgot to enter your city!</li>";}
if(empty($_POST['postcode'])){$errorMessage .= "<li>You forgot to enter your zip code!</li>";}
$name = $_POST['name'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$city = $_POST['city'];
$state = $_POST['state'];
$postcode = $_POST['postcode'];
$csvData = $name . "," . $email . "," . $address1 . "," . $city . "," . $state . "," . $postcode ."\n";
if(empty($errorMessage)){
$fs = fopen("contest.csv","a");
fwrite($fs,$csvData);
fclose($fs);
header("location: thank you");
exit;
}
}
我在想我将我的fopen更改为r+
而不是a
,然后读取csv文件以检查地址。然后把另一个if语句放到中继'发现重复'或者fwrite
s信息并将它们发送到感谢页面。
答案 0 :(得分:0)
正如一些评论中所提到的,平面文件并不是解决此类问题的最佳解决方案,但正如您所提到的那样,使用已经存在的内容并转移到其他功能上更容易(也更便宜)。
如果您使用的是数据库,则可以在不希望出现重复数据的列上添加唯一约束,并在数据库层为您处理此重置功能。虽然您必须处理尝试插入时返回的错误,但它是一个更优雅的解决方案。
但是,如果您希望继续使用CSV解决方案,则必须解析现有CSV并推断现有地址,然后您可以检查表单提交地址是否已存在。
// Pseduo code
User submits form
Open up existing CSV file
Step through each entry in csv file
Store Address in $addresses[] array
Check if user submitted address exists in $addresses[] array
正如您所看到的,此解决方案不具备性能,因为每次提交表单时都必须打开,解析和检查,但它应该可以实现您的目标。
如果psuedo代码不够,请告诉我,我可以编写代码。
- 编辑 -
以下是一些链接,可帮助您了解如何集成数据库解决方案以解决问题。这些只是为了让您入门,因为有关于该主题的大量信息:
数据库设计:http://en.wikipedia.org/wiki/Database_design
Vanilla与数据库的交互(使用PHP):http://php.net/manual/en/book.pdo.php
ORM与数据库的交互(使用PHP):http://www.doctrine-project.org/