php - SQLSTATE[HY093] : Invalid parameter number: no parameters were bound, 但提供了参数

标签 php pdo

我正在构建一个数据库对象,它将 PDO 对象与 PDOStatement 对象连接起来,以便链接可用。基本上我只是把我最常用的方法放在一起,但是 bindParam 让我很难受。

private $stmt = null;

...

public function prepare($statement,array $driver_options = array()) {
    if($this->stmt) throw new \Exception('PDO Statement already prepared, no override!');
    $this->stmt = parent::prepare($statement, $driver_options);
    return $this;
}

public function bindParam($place, &$val, $dataType){
    if(!$this->stmt) throw new \Exception('PDO Statement is empty');
    $this->stmt->bindParam($place, $val, $dataType);
    return $this;
}

public function execute(array $params = array()){
    if(!$this->stmt) throw new \Exception('PDO Statement is empty');
    $this->stmt->execute($params);
    return $this;
}

public function fetchAll($pdoFetchType){
    if(!$this->stmt) throw new \Exception('PDO Statement is empty');
    return $this->stmt->fetchAll($pdoFetchType);
}

...

public function getStmt(){
    return $this->stmt;
}

public function clearStmt(){
    $this->stmt = null;
}

我在这段代码中从标题中得到了错误:

$i = 0;
$db->prepare('SELECT * FROM users LIMIT ?,1')->bindParam(1, $i, \PDO::PARAM_INT);
while($row = $db->execute()->fetchAll(\PDO::FETCH_ASSOC)){
    echo "<pre>".print_r($row, true)."</pre>";
    $i++;
}

基本上我发现这个错误是当 bindParam 中提供的变量为 null 时发生,但 $i 显然不是无效的。你能帮帮我吗?

编辑:也在运行

var_dump($this->stmt->bindParam($place, $val, $dataType));

bindParam 方法中返回TRUE。来自手册:

Return Values

Returns TRUE on success or FALSE on failure.

成功了但是没有绑定(bind)参数???我感觉我的脑子快要爆炸了。

最佳答案

我想使用引用 &$val 而不是值 $val 是导致问题的原因。

请尝试使用此代码:

public function bindParam($place, $val, $dataType)
{
    if(!$this->stmt) throw new \Exception('PDO Statement is empty');
    $this->stmt->bindParam($place, $val, $dataType);
    return $this;
}

编辑

我上面的回答是错误的。

尝试修改execute方法:

public function execute(array $params = array()){
    if(!$this->stmt) throw new \Exception('PDO Statement is empty');
    $this->stmt->execute();
    return $this;
}

将空数组作为参数传递给 execute 方法会删除所有先前的绑定(bind)。这就是为什么 bindParam 返回 true(成功绑定(bind)),但是当您调用 execute 时,“no params were bound”错误出现。

关于php - SQLSTATE[HY093] : Invalid parameter number: no parameters were bound, 但提供了参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20436745/

相关文章:

email - 使用 msmtp 通过终端发送邮件工作正常,但不适用于 php mail()

php - 使用 yii2 进行生产

php - mySQL 到 PHP 到 jQuery 返回浮点值作为字符串 (JSON)

php - 使用外键插入表 - PHP PDO

php - 如何修复 stmt->execute() 总是返回 false?

php - 如何使用 PDO 从 MySQL 获取数字类型?

php - 如何向mysql数据库中插入随机值?

php - Yii 不明白如何记录消息

php - PDO 中的 "SELECT :parameter FROM .."

pdo - 持久数据库连接 - 是还是否?