我正在构建一个数据库对象,它将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
。从手册:
返回值
成功时返回TRUE,失败时返回FALSE。
它成功但没有绑定参数???我觉得我的大脑很快就会爆炸。
答案 0 :(得分:12)
我想使用引用&$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
方法会删除所有先前的绑定。这就是bindParam
返回true(成功绑定)的原因,但是一旦调用execute
,就会出现“没有参数被绑定”错误。
答案 1 :(得分:5)
得到了相同的错误,但原因不同
我的请求有评论,其中一条包括该死的问号。
对于PDO,“?
”当然是要绑定的参数。
我的请求在其他任何地方都没有问题,我不知道PDO会在我没有使用任何内容时发明“参数”,因为我总是使用命名占位符,例如 {{1 }}
在这上花了一个多小时:(
这个答案可以帮助一些人解决这个愚蠢的问题。