Hello - i would really appreciate some help with this. I think its quite a simple issue and i can see why its not working - just dont know how to fix it!
I have a stock search form. The top half of which, users enter their contact details and the bottom half are the stock results. The user searches for a product, enters their details, checks the products they want and enters the corresponding quantities. They then hit send and it will be mailed away.
I have some basic error checking on each field, for example:
// Check to make sure that the First Name field is not empty, and that it does not contain badwords or exploits
if(trim($_POST['first-name']) == '' ) {
$error['first-name'] = "You didn't enter your <b>First Name</b>.";
} else if (preg_match($badwords, trim($_POST['first-name'])) !== 0 || preg_match($exploits, trim($_POST['first-name'])) !== 0) {
$error['first-name'] = "You entered a <b>First Name</b> which contains unacceptable or explicit words.";
} else {
$first_name = trim(filter_var($_POST['first-name'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
unset($error['first-name']);
}
If there are any errors they are then displayed:
// If there are any errors
if(isset($error)) {
echo '<h1>Your Message Has Not Been Sent</h1>';
echo '<p>Unfortunately your message was <b>not</b> sent as the following errors were detected:</p>';
echo '<ul>';
foreach($error as $errorViolation){
echo '<li> '.$errorViolation.' </li>';
}
echo '</ul>';
echo '<p>Please <a href="javascript:history.go(-1)">go back and correct these errors.</a></p>';
exit();
}
My problem is, i am trying to ensure that for each product checked a corresponding quantity is also entered. I have:
// Foreach of the parts selected (the id array), select the value corresponding to each key
foreach($_POST['id'] as $key=>$value){
$quantity_value = $_POST['quantity'][$key];
if(trim($quantity_value) == '') {
$error['quantity'] = 'You didn\'t enter a <b>Quantity</b> for ' . $_POST['part-number'][$key];
} elseif(preg_match($badwords, trim($quantity_value)) !== 0 || preg_match($exploits, trim($quantity_value)) !== 0) {
$error['quantity'] = 'You entered a <b>Quantity</b> which contains unacceptable or explicit words for ' . $_POST['part-number'][$key];
} else {
$quantity_value = trim(filter_var($_POST['company-name'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
unset($error['quantity']);
}
}
Which kinda works, but as you can probably see each for multiple parts (with multiple quantites missing), the foreach loops through and overwrites any previous error - meaning i am only left with one error message - when there should be one for each missing part. I want to write something like:
$error['quantity'][$key] = 'You didn\'t enter a <b>Quantity</b> for ' . $_POST['part-number'][$key];
But that breaks the errors while loop (the error just displays Array). Sorry i was rather long winded in my explanation. Any help would be greatly appreciated
Cheers