PHP验证帮助。名字和姓氏,验证为必填字段

时间:2016-02-27 07:29:28

标签: php

此链接指向我的代码运行位置。

http://erobi022.pairserver.com/phpvalidate1.php

<!DOC TYPE html>
<html>
<body>
This is a simple form
<form method="post" action="send_phpvalidate1.php">

Please enter your first name: <input type="text" name="First"></p>

Please enter your last name: <input type="text" name="Last"></p>

<button type="submit">Submit</button>
</form>
</body>
</html>

点击提交按钮后,所有数据都会在此处发送和发布。我可以得到名字和姓氏输出正常,但如果我把它们留空,它只会说我把我的名字字段留空了。

http://erobi022.pairserver.com/send_phpvalidate1.php

<!DOCTYPE html>
<html>
<body>
Welcome, 
</P>
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name1 = $_POST["First"];
    if (empty($name1)) {
        echo "You've entered nothing for first name";
        echo "<br>";
        echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
        die; //if you mess up, youll have to fix it
    } else {
        echo " Your first name is $name1 ";
    }
}

echo "<br>";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name2 = $_POST["Last"];
    if (empty($name2)) {
        echo "You've entered nothing for last name";
        echo "<br>";
        echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
        die; //if you mess up, youll have to fix it
        } else {
         echo " Your last name is $name2 ";
    }
}

?>


<?php // can have multiple php sections

echo "<a href='phpvalidate1.php'>Return to form</a></p>";
//have to use a simple qoute within html to make it work


?> </p>

<a href=".">Return to home page</a>

</body>
</html>

3 个答案:

答案 0 :(得分:0)

无需使用两个大的if,只需用以下代码替换您的PHP代码:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name1 = $_POST["First"];
    $name2 = $_POST["Last"];
    if (empty($name1) || empty($name2)) {
        echo "Please complete both the fields.";
        echo "<br>";
        echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
        die; //if you mess up, youll have to fix it
    } else {
        echo " Your name is $name1 $name2";
    }
}
?>

答案 1 :(得分:0)

您可以使用HTML 5,简单

来使用它
<!DOC TYPE html>
<html>
<body>
This is a simple form
<form method="post" action="send_phpvalidate1.php">

Please enter your first name: <input  required="required"  type="text" name="First"></p>

Please enter your last name: <input  required="required"  type="text" name="Last"></p>

<button type="submit">Submit</button>
</form>
</body>
</html>

答案 2 :(得分:0)

首先,每当有一个die()语句时,只有在运行之前出现的代码,那些在不运行之后的代码(与您的代码相关)。

您也可以通过这种方式修剪代码,它仍然有效

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name1 = $_POST["First"];
$name2 = $_POST["Last"];
if (empty($name1) || empty($name2)) {
    echo "Please complete both the fields.";
    echo "<br>";
    echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
    die; //if you mess up, youll have to fix it
} else {
    echo " Your name is $name1 $name2";
 }
}
?>