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

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 に答える