首页 > 解决方案 > 用 PDO 编写插入代码的最佳方法是什么?

问题描述

我最近学习了面向对象编程PHP,我试图测试我的知识,所以我尝试自己写一些查询......

(示例实践:插入新行、更新行和删除行)。

这是我自己编写的模板,以便将新行插入数据库

class Register
{   
    protected $notice = array();
    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";
                return $this->notice;
            }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";
                    return $this->notice;
                }else{
                    $this->NewAdmin($username,$email,$password,$groups,$level);
                    $notice['success_message'] = "New admin was successfully added";
                    return $this->notice;
                }
            }
        }
    }
    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();
        }
    }
    public function getNotice()
    {
        return $this->notice;
    }
}

我在索引上调用了这个类:

    <?php 
if (isset($_POST['submit'])){
    $username = $_POST['uname'];
    $email = $_POST['email'];
    $password = $_POST['pass'];
    $groups = $_POST['groups'];
    if($groups == "Administrator"){
        $level = 2;
    }else if($groups == "ContentCreatorBlog"){
        $level = 3;
    }else if($groups == "ContentCreatorShop"){
        $level = 4;
    }else if($groups == "ContentCreatorGallery"){
        $level = 5;
    }else if($groups == "Secretary"){
        $level = 6;
    }else if($groups == "SocialMediaManager"){
        $level = 7;
    }else if($groups == "Analyst"){
        $level = 8;
    }else{
        $level = Null;
    }
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $notice['email_validation'] = "The email that you have entered is not a valid one";
    }else{
        $registration = new Register();
        $notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);   
    }   
}
?>
<div class="content-wrapper">
    <section class="content-header">
        <h1>
            Add New Admin
            <small>You can add new admin here</small>
        </h1>
        <ol class="breadcrumb">
            <li class="active">addnewadmin.php</li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary" id="myModal1">
                    <div class="box-header with-border">
                        <h3 class="box-title">Required Information</h3>
                    </div>
                    <?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>
                        ";
                    }
                    ?>
                    <form role="form" method="POST" action="" data-tour-index="1" data-tour-title="Card Type" data-tour-description="A card will usually be one of multiple similar type items on a page.">
                        <div class="box-body">
                            <div class="form-group">
                                <label>User name</label>
                                <input type="text" class="form-control" placeholder="Enter username" name="uname" required>
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Email address</label>
                                <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">Temporary password</label>
                                <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
                            </div>
                            <div class="form-group">
                                <label>Group admin</label>
                                <select class="form-control" name="groups">
                                    <option value="Administrator">Administrator</option>
                                    <option value="ContentCreatorBlog">Blog Content Creator</option>
                                    <option value="ContentCreatorShop">Shop Content Creator</option>
                                    <option value="ContentCreatorGallery">Gallery Content Creator</option>
                                    <option value="Secretary">Secretary</option>
                                    <option value="SocialMediaManager">Social Media Manager</option>
                                    <option value="Analyst">Analyst</option>
                                </select>
                            </div>
                        </div>
                        <div class="box-footer">
                            Visit <a href="https://zite.pouyavagefi.com/documentation/adminnew.php">admin new</a> documentation to know more about this page.
                        </div>
                        <div class="box-footer">
                            <button name="submit" type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
</div>

所以很快它所做的就是显示表单并获取一些信息并分配给参数,然后调用类:

$registration = new Register();
$notice[] =      $registration->CheckUname($username,$email,$password,$groups,$level);  

因此,如果表单遇到任何错误,例如:

already registerd username error
already exists email address error

它应该简单地收回error message并通过索引页面上的这些代码向用户显示:

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>
    ";
}

问题:

此代码的问题在于,尽管有规则,但当用户输入信息时不会弹出错误消息。但是它仍然正确地向表中添加新行。

所以现在的问题是“为什么当用户输入错误信息时错误没有显示在页面上?我犯了哪一部分错误”

标签: phpmysqlmysqli

解决方案


$notice和之间有区别$this->notice$notice是一个局部变量并且$this->notice是一个类变量。在您的情况下,您只创建一个本地变量,分配一个值,但返回仍然为空的类变量。

要解决此问题,只需将其替换为$this->notice[..] = ....

但也有其他逻辑问题。为什么要CheckUname创建用户?这将是NewAdmin调用的任务CheckUname。您也可以将两个数据库查询合并为一个,询问是否有带有用户名或密码的条目。还有更多需要修复/更改,但这将是代码审查的一部分


推荐阅读