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


PHP validation help. First and last name, validated as required fields

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

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>

你可以用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>

不需要使用两个大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";
    }
}
?>

首先,每当有 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";
 }
}
?>