I have a PHP script that is processing some form data (by posting back to itself) and displaying the relevant form data in the form along with the resulting calculations. The relevant pieces of code that I'm having trouble with are shown below:
First bit of code:
if ($_POST["country"] == "select") {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
}
else {
$country = ($_POST["country"]);
}
Second bit of code is as follows. Note that my intent is to trigger an error message if data entered into the zip field is not a 5-digit zip code:
if (empty($_POST["zip"])) {
if ($country == "United States") {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
}
else {
if ($country == "United States") {
$zipCode = test_input($_POST["zip"]);
if (!preg_match("/^[0-9]{5}$/",$zipCode)){
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
//$zip="";
}
}
}
}
Relevant code in form for zip code:
<input id="zip" type="text" name="zip" placeholder="Enter 5-digit zip code" value="<?php echo $zipCode;?>" />
With respect to the processing of form data, the zip code isn't working correctly:
Clearly, I've got something wrong with my logic / expression, but I've been looking at this for a while. If anyone has some suggestions, it would be appreciated.
Cheers! Mike
Let's format the code and see what we're dealing with:
if (empty($_POST["zip"])) {
if ($country == "United States") { //WHAT? Then if you're from US you're always going to hit this part
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
} else {
if ($country == "United States") { //this is never going to hit because of that top part
$zipCode = test_input($_POST["zip"]);
if (!preg_match("/^[0-9]{5}$/", $zipCode)) {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
//$zip="";
}
}
}
}
Hope this helps you, you need to remove that top part really...
if (empty($_POST["zip"])) { //you can add && $country == "United States" here if you want for exclusive logic, like if other countries don't *require* the zip
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
} else {
if ($country == "United States") {
$zipCode = test_input($_POST["zip"]);
if (!preg_match("/^[0-9]{5}$/", $zipCode)) {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
//$zip="";
}
}
}