PHP脚本未显示字段


PHP script not displaying field

我有一个PHP脚本,它正在处理一些表单数据(通过发布回自己),并在表单中显示相关的表单数据以及由此产生的计算。我遇到问题的相关代码如下所示:

代码的第一位:

   if ($_POST["country"] == "select") { 
    $formResponse = "Some data was incorrectly entered or missing. Please try again.";
    }
    else {
    $country = ($_POST["country"]);
}

代码的第二位如下。请注意,如果输入zip字段的数据不是5位邮政编码,我的意图是触发一条错误消息:

   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="";
            }
        }
    }
}

邮政编码表格中的相关代码:

<input id="zip" type="text" name="zip" placeholder="Enter 5-digit zip code" value="<?php echo $zipCode;?>" />

关于表单数据的处理,邮政编码无法正常工作:

  1. if(空(($POST["zip"]);这段代码工作正常,并在表单提交时抛出正确的错误
  2. 我的RegEx似乎不起作用,因为如果任何类型的数据被放入zip字段,它都不会抛出错误,并表明所有数据都已正确提交
  3. 在"成功"处理时,不会显示$zipCode字段

很明显,我的逻辑/表达有问题,但我已经看了一段时间了。如果有人有什么建议,我们将不胜感激。

干杯!Mike

让我们格式化代码,看看我们正在处理什么:

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="";
            }
        }
    }
}

希望这能帮助你,你真的需要去掉顶部。。。

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="";
        }
    }
}