pdo mysql insert在多个字段中放置相同的东西

时间:2012-10-12 17:27:09

标签: php pdo

好的,出于某种原因这个查询:

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

将“random_string”输入每个字段,我不知道为什么。

这是我的查询代码:

    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());
    }
}

知道为什么会这样做吗?

1 个答案:

答案 0 :(得分:2)

PDO参数通过引用绑定。因此,所有参数都被绑定为对同一$p变量的引用,该变量在执行查询时的值是数组的最后一个元素。

虽然你说在所有字段中插入的值是数组的 second 元素。我不确定为什么会这样。

解决方案是使用bindValue代替bindParam