如何使用PHP在一个页面中验证两个表单?每个表单都重定向到同一页

时间:2015-11-05 20:42:46

标签: php forms

这是我用于验证搜索表单的代码,我在不同的标签中有两个表单。一次只提交一个表单,但由于验证显示错误

<?php
$foutcityErr = $toutcityErr = $dateoutErr = "";
$foutcity = $toutcity = $dateoutErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $valid = true;
    if (empty($_POST["foutcity"])) {
        $foutcityErr = "Please type source";
        $valid = false;
    } else {
        $foutcity= test_input($_POST["foutcity"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$foutcity)) {
            $foutcityErr = "Only letters and white space allowed"; 
            $valid = false;
        }
    }
    if (empty($_POST["toutcity"])) {
        $toutcityErr = "Please type destination";
        $valid = false;
    } else {
        $toutcity= test_input($_POST["toutcity"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$toutcity)) {
            $toutcityErr = "Only letters and white space allowed"; 
            $valid = false;
        }
    }
    if (empty($_POST["$dateoutErr"])) {
        $dateoutErr = "Please choose loading date";
        $valid = false;
    }
    else {
        $dateout= test_input($_POST["dateout"]);
    }
    if($valid){
        setcookie('foutcity',$foutcity);
        setcookie('toutcity',$toutcity);
        setcookie('dateout',$dateout);
        header('Location:resultout.php');
        exit();

    }
}
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}}?>

我对表单使用相同的验证方法,一个表单将提交一次。

1 个答案:

答案 0 :(得分:0)

要在您的PHP代码中了解提交的表单,请在第一个表单中添加:

 <input type="hidden" name="form_number" value="1"/>

并以第二种形式添加:

 <input type="hidden" name="form_number" value="2"/>

然后在PHP代码中,在$_SERVER["REQUEST_METHOD"]测试之后,执行:

 if ($_POST["form_number"] == "1") {
     // your code for form 1
 } else {
     // your code for form 2
 }

你的代码中也有错误:有11个开口大括号,12个大括号:这是不正确的。您没有给出所有代码,并且test_input块中定义了if { }函数:然后在代码执行到达该点之前它不存在。将它移出块。

或者你最后有一个关闭括号太多:删除它。

我还会改进你的代码缩进。