首先,这不是编写整体代码的最佳方法,但我正在尝试练习switch语句,因此我使用相同的表单和错误消息来练习不同的php函数和语句等
在这种特殊情况下,案例编号(案例1,案例2,案例3等)都包含在我的echo语句中,我不知道为什么
因此,在给出的示例中,在用户名下的表单中输入字母C并期望错误输出为"用户名必须至少为6个字符"但是实际出现的是什么"用户名必须至少为6个字符2"
我已尝试将各种if语句的初始变量设置的数字值放入""当我得到case switch语句时,如果它必须作为文本读取,但这没有任何区别
对此有任何帮助将不胜感激。可能非常简单。请不要嘲笑我的代码......太多了
`
<?php
##### Form Handling ####
if ( $_SERVER[ 'REQUEST_METHOD'] == 'POST')
### Error Handling ###
// define variables and set to empty values
$userErr = $firstnameErr = $surnameErr = $emailErr = "";
$user = $firstname = $surname = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["user"]))
{
$userErr = 1;
}
else
{
$user = $_POST["user"];
if (strlen($user) < 6) {
$userErr = 2;
}
if(strlen(trim($username)) != strlen($username)) {
$userErr = 3;
}
}
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is required";
} else {
$firstname = $_POST["firstname"];
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed"; }
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = $_POST["surname"];
if (!preg_match("/^[a-zA-Z ]*$/",$surname))
{$surnameErr = "Only letters and white space allowed"; }
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = $_POST["email"];
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{ $emailErr = "Invalid email format"; }
}
}
?>
<form action="form_register.php" method="POST">
<p>Username:
<input type="text" name="user" value="<?php echo $user;?>">
<?php
switch($userErr)
{
case 1:
echo "Username is required";
break;
case 2:
echo "Username must be a minimum of 6 characters";
break;
case 3:
echo "Must not contain any spaces";
break;
default:
echo "*";
break;
}
echo $userErr;?> </p>
<p>First Name:
<input type="text" name="firstname" value="<?php if ( isset ($_POST['firstname']))
echo $_POST['firstname'] ; ?>"> </p>
<p>Surname:
<input type="text" name="surname" value="<?php if ( isset ($_POST['surname']))
echo $_POST['surname'] ; ?>"> </p>
<p>Email Address:
<input type="text" name="email" value="<?php if ( isset ($_POST['email']))
echo $_POST['email'] ; ?>"> </p>
<p><input type="submit"></p>
</form>
`
答案 0 :(得分:1)
直接在案件阻止之后,您回复了号码本身:
echo $userErr;?>
删除echo
,它应该可以正常工作。