I have an issue I want to have a php file set on my server that appends to a csv file and also reads and queries that csv file for a column.

eg:

I want a csv file with the following columns
Email, First, name

I want the php to query the csv and evaluate if form.email is the same as any email in the csv file then throw and error.

If the email is not in the list and is a valid email then go ahead and append a line to the csv file with the required columns.

I am a php novice so if anyone can help me I appreciate it.

i have a script i just made for you but i have to ask if you need me to add email validation to it. also, does it need to have input fields for the first name column?

here it is:

<form action="csv.php" method="post">
<p>Email:<input type="text" name="email" /></p>
<p>Name:<input type="text" name="name" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
<?php
if (isset($_POST['submit'])) {
function check($fieldname)
{
if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\@\ ]+$/s",$fieldname)) {
return TRUE;
}
else {
return FALSE;
}
}
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$error = 0;
if ($email == NULL) {
$error_msg .= "Email field is not filled out\\n\\n";
$error++;
}
if (!$email == NULL && !check($email)) {
$error_msg .= "Email field contains illegal characters\\n\\n";
$error++;
}
if ($name == NULL) {
$error_msg .= "Name field is not filled out\\n\\n";
$error++;
}
if (!$name == NULL && !check($name)) {
$error_msg .= "Name field contains illegal characters\\n\\n";
$error++;
}
if ($error > 0) {
$error_msg .= "There currently are " . $error . " errors";
echo '<script type="text/javascript">alert ("' . $error_msg . '");</script>';
}
if ($error == 0) {
$row = 1;
$open = fopen("file.csv", "r");
while (($data = fgetcsv($open, 1000, ",")) !== FALSE) {
if ($data[0] == $email) {
die('email already exists');
}
}
fclose($open);
$csv = $email . ", " . $name . "\n";
$open = fopen("file.csv", "a");
$write = fwrite($open, $csv);
fclose($open);
}
}
?>
This article has been dead for over six months. Start a new discussion instead.