I have drawn up the following PHP code which processes the data from a form in the following way:
- Adds all of the names entered to an array.
- Checks if any of the names are in a MySQL table.
- If not, returns an error.
- If so, adds data to a column called ‘workshop’ in the table for the names submitted.
$emailFrom = "";
$emailTo = "";
$subject = "Booking(s) for Workshop";
$body = "The following people have booked their workshops:" . "\n\n";
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
$query = "SELECT 1 FROM conference WHERE Name In $names";
$result = mysql_query($query);
if ($result) {
$rowcount = mysql_num_rows($result);
if ($rowcount == 0) {
$errorString = "No bookings found";
}
else {
for($i = 0; $i < $row_count; $i++) {
$sql = "UPDATE conference SET Workshop = '$workshop[$i]' WHERE Name LIKE '$name[$i]'";
mysql_query($sql);
}
}
}
}
include 'workshops.php';
// send email
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks-workshop.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
//}
The issue I am now facing is how to add more sophisticated error checking. I want the PHP to check each name submitted on the form. If it finds all of the names, submit the data to the workshop column. If any names are not found, the error message would read “The following names have not been found on our database: [names listed]”. The user would then be forced to enter the correct names or remove the offending names, before the form could be submitted. I have got my head into a bit of tangle trying to work out how to achieve this though.
Should I run a separate query on the first loop for each name, and then if the name is not found in the table, add that name to a variable which would then be included in the error message? Then, if after all of the loops the error variable is “”, the form could be submitted (because all names have been found), but if not the error message would show the names that need amending?
Would this be the best method, or is there a better way?
I need to say sorry. I assumed you are sending all names thru POST.
Here is second solution, try it: