0

我有一些方法可以将一些数据插入到这样的数据库中:

public function register($username, $email, $hashedPassword, $activationCode)
    {
        try {
            $conn = Database::getConnection();
            // Connect and create the PDO object
            $conn->exec('SET CHARACTER SET utf8');      // Sets encoding UTF-8
            // Define and prepare an INSERT statement
            $sql = 'INSERT INTO users (username, email, pass, reset_token, dateAdded )
            VALUES (:username, :pass, :email, :token, now())';
            $sqlprep = $conn->prepare($sql);

            // Adds value with bindParam
            $sqlprep->bindParam(':username', $username, PDO::PARAM_STR);
            $sqlprep->bindParam(':email', $email, PDO::PARAM_STR);
            $sqlprep->bindParam(':pass', $hashedPassword);
            $sqlprep->bindParam(':token', $activationCode);

            // If the query is successfully executed, output the value of the last insert id
            if ($sqlprep->execute()) {
                //echo 'Succesfully added the row with id='. $conn->lastInsertId();
                $this->result = true;
            }
            $conn = null;        // Disconnect

        } catch (PDOException $e) {
            include('../views/error.php');
            include('../views/admin/includes/footer.php');
            exit();
        }
    }

问题是我认为如果我的函数有这么多参数要输入数据库,这不是一个好方法。那么我可以通过使用 1 个参数但仍然使用 bindParam 来输入很多字段有什么好的方法吗?由于我看到很多示例仅使用没有 bindParam 的准备。我想我可以使用数组,但我不知道正确的方法。所以我需要一些帮助,我该怎么做。

4

3 回答 3

0

您可以将参数作为数组插入到$sqlprep->execute($param_array) Or 中,只需将每个参数传递到执行内部的数组中,如下所示:$sqlprep->execute(array($param1, $param2))

更新:

将值作为数组传递给 $input:

$input = array('username' => $username, 'activationHash' => $activationHash); //and so on

现在在模型方面,您可以使用 foreach 循环将这些值绑定到参数,如下所示:

foreach ($values as $key => $value) {
        $sqlprep->bindParam(':' . $key, $value , PDO::PARAM_STR);
    }
于 2015-03-19T09:18:01.160 回答
0

https://stackoverflow.com/a/10060755/1747411
检查第二个示例,您必须使用绑定重复值,
例如
VALUES (:username1, :pass1, :email1, :token1, now()), (:username2, :pass2 , :email2, :token2, now())
和 bindParam 与循环

于 2015-03-19T09:21:31.913 回答
0

因为你想保留你的 bindparam 我建议你使用这样的输入:

$input = array('username' => $username, 'activationHash' => $activationHash);

并在您的 bindParam 添加如下代码:

public function register($input){
//code

$sqlprep->bindParam(':username', $input['username'], PDO::PARAM_STR);

//other
}

希望这能解决你的问题

于 2015-03-20T08:09:43.020 回答