0

我有一个用户类,我想知道处理插入的“最推荐”方式是什么?

选项 1:使用现有对象

// insert a new user and return the user id
public function insert() {
    $sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
                              (?, ?, ?, ?, ?, ?, ?, ?)";
    $sth = $this->db->prepare($sql);
    $sth->bindParam(1, $this->username, PDO::PARAM_STR);
    $sth->bindParam(2, $this->password, PDO::PARAM_STR);
    $sth->bindParam(3, $this->email, PDO::PARAM_STR);
    $sth->bindParam(4, $this->avatar, PDO::PARAM_STR);
    $sth->bindParam(5, $this->subscribe, PDO::PARAM_STR);
    $sth->bindParam(6, $this->created, PDO::PARAM_STR);
    $sth->bindParam(7, $this->last_login, PDO::PARAM_STR);
    $sth->bindParam(8, $this->valid, PDO::PARAM_STR);
    $sth->execute();

    return $this->db->lastInsertId();
}

选项2:将信息作为数组传递

// insert a new user and return the user id
public function insert(array $fields = array()) {
    if(!empty($fields)) {
        $sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
                                  (:username, :password, :email, :avatar, :subscribe, :created, :last_login, :valid)";
        $sth = $this->db->prepare($sql);
        $sth->execute($fields);

        return $this->db->lastInsertId();
    }
}

另外一个选项?它有什么不同吗?

4

1 回答 1

0

两种方式都可以,但我个人建议第二种选择

于 2013-02-02T17:28:51.787 回答