【问题标题】:PDOStatement::bindParam doesn't work after the first callPDOStatement::bindParam 在第一次调用后不起作用
【发布时间】:2019-03-19 05:03:20
【问题描述】:

我在编写一个使用 PDO 连接到数据库的简单类时遇到了一点问题。
问题是 PDOStatement::bindParam 在循环中的第一次调用后不起作用,我的意思是如果我有两个参数要给 PDOStatement 查询不会返回 rignt 结果,而是如果我只给出一个参数它给出了正确的结果。

代码如下:

public function query($sql, $params = NULL) {
        // Opens the PDO connection
        $this->open();

        $this->stmt = $this->pdo->prepare($sql);

        if (isset($params)) {
            foreach ($params as $key => $value) {
                // This doesn't work after the second cicle.
                $this->stmt->bindParam(':' . $key, $value);
            }
        }

        $result = NULL;
        if (!$this->stmt->execute()) {
            $result = false;
        } else {
            $result = $this->stmt->fetchAll();
        }

        // Closes the PDO connection
        $this->close();

        return $result;
}

这是 PDOStatement::debugDumpParams:

SQL: [114]
SELECT 1
FROM   users
WHERE  EXISTS
       (
              SELECT *
              FROM   users
              WHERE  username = :username
              AND    password = :password) limit 1
PARAMS: 2
KEY:NAME: [9] :username paramno=0 NAME=[9] ":username" is_param=1 param_type=2
KEY:NAME: [9] :password paramno=1 NAME=[9] ":password" is_param=1 param_type=2  

感谢您的帮助!

【问题讨论】:

  • 你在其他表上试过了吗?至于使用它来匹配用户名和密码,你真的应该考虑使用password_hash()
  • @NigelRen 我正在使用 md5() 函数和盐字符串来散列然后存储密码,这还不够吗?是的,我已经在其他桌子上试过了
  • 好的,我发现了问题。我使用 PDOStatement::bindValue 而不是 bindParam 修复了它。

标签: php sql pdo pdostatement


【解决方案1】:

TL;DR 始终使用 bindValue(),除非您想使用 bindParam() 的特殊行为。

foreach ($params as $key => $value) {
    // This doesn't work after the second cicle.
    $this->stmt->bindParam(':' . $key, $value);
}

这不能按预期工作的原因是对 PDO 对 bindParam() 的含义的误解。这并不意味着“绑定 SQL 参数”,而是“将值(即 bindParam() 的参数)绑定为引用变量”。因此,当调用execute() 时,它将在执行时使用$value 的值(这是绑定到所有SQL 参数的变量),而不是在调用bindParam() 时。

参照。 http://php.net/manual/en/pdostatement.bindparam.php 解释了这种行为。

解决方案是使用bindValue() 而不是bindParam()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多