NaughtySquid
NaughtySquid

Reputation: 2097

pdo mysql insert puts the same thing in multiple fields

Okay so for some reason this query:

$db->sqlquery("INSERT INTO `password_reset` SET `user_email` = ?, `secret_code` = ?, `expires` = ?", array($email, $random_string, $next_week));

Enters "random_string" into every field and I have no idea why.

This is my query code:

    public function sqlquery($sql, $objects = array())
{
    global $core;
    try
    {
        $this->STH = $this->database->prepare($sql);

        foreach($objects as $k=>$p)
        {
            // +1 is needed as arrays start at 0 where as ? placeholders start at 1 in PDO
            if(is_numeric($p))
            {
                $this->STH->bindParam($k+1, $p, PDO::PARAM_INT);
            }
            else
            {
                $this->STH->bindParam($k+1, $p, PDO::PARAM_STR);
            }
        }


        return $this->STH->execute();

        $this->counter++;
    }

    catch (PDOException $e)
    {
        $core->message($e->getMessage());
    }
}

Any idea why it would be doing that?

Upvotes: 2

Views: 145

Answers (1)

Barmar
Barmar

Reputation: 781741

PDO parameters are bound by reference. So all your parameters are being bound as references to the same $p variable, whose value when executing the query is the last element of the array.

Although you said that the value being inserted in all the fields is the second element of the array. I'm not sure why that is.

The solution is to use bindValue instead of bindParam.

Upvotes: 2

Related Questions