PHP:如何在表单注册后显示表单错误消息

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (108)

我想创建一个类,它可以从表单中获取一些值并插入一个新的MySQL表行。

如果错误地提交了值,则会设置一个错误变量并显示在页面上。

这是我尝试制作课程:

<?php 
class Register
{   
    private $_db;
    public function __construct()
    {
        $this->_db = new Connection();
        $this->_db = $this->_db->dbConnect();
    }
    public function CheckUname($username,$email,$password,$groups,$level)
    {
        if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
        {
            $chk1 = $this->_db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
            $chk1->bindParam(1,$username);
            $chk1->execute();
            if($chk1->rowCount() == 1)
            {
                $notice['username_exists'] = "Try different username";
            }else{
                $chk2 = $this->_db->prepare("SELECT email_address FROM admins WHERE email_address = ?");
                $chk2->bindParam(1,$email);
                $chk2->execute();
                if($chk2->rowCount() == 1)
                {
                    $notice['email_exists'] = "The email address that you have entered is already exists in database";
                }else{
                    $this->NewAdmin($username,$email,$password,$groups,$level);
                    $notice['success_message'] = "New admin was successfully added";
                }
            }
        }
    }
    public function NewAdmin($username,$email,$password,$groups,$level)
    {
        if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
        {
            $reg = $this->_db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
            $reg->bindParam(1,$username);
            $reg->bindParam(2,$email);
            $reg->bindParam(3,$password);
            $reg->bindParam(4,$groups);
            $reg->bindParam(5,$level);
            $reg->execute();
        }
    }
}
?>

在包含注册表单的页面上,我放置了这些代码以便在屏幕上打印错误:

<?php 
if(isset($notice['email_validation'])){
echo "
<div class='alert alert-danger'>
    <strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])){
echo "
<div class='alert alert-danger'>
    <strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
    <strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
    <strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>

但现在问题是,如果您提交的表单中包含错误的数据,repeated email address或者invalid username,错误变量将被提交并显示在屏幕上。

提问于

扫码关注云+社区

领取腾讯云代金券