在我的DB类中,我有一个方法query(),它将SQL语句和参数作为参数,并在数据库中运行它们。
// the parameters are the sql statement and the values, returns the the current object
// the result set object can be accessed by using the results() method
public function query($sql, $params = array()) {
$this->_error = false; // initially the error is set to false
if($this->_query = $this->_pdo->prepare($sql)) {
// if the parameters are set, bind it with the statement
if(count($params)) {
foreach($params as $param => $value) {
$this->_query->bindParam($param, $value);
}
}
// if the query is successfully executed save the resultset object to the $_results property
// and store the total row count in $_count
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}我就是这样调用这个方法的
$db->query("SELECT * FROM users WHERE username = :username AND id = :id ", array(':username' => 'sayantan94', ':id' => 1));但是,当我print_r()结果集时,我将得到一个空数组。但如果我这么做
$db->query("SELECT * FROM users WHERE username = :username", array(':username' => 'sayantan94'));或者这个
$db->query("SELECT * FROM users WHERE id = :id ", array(':id' => 1));我正在得到正确的结果。我的密码怎么了??
发布于 2016-08-29 11:04:30
除了在另一个答案中所说的,你的大部分代码要么是无用的,要么是有害的。事实上,你只需要这几行
public function query($sql, $params = array())
{
$query = $this->_pdo->prepare($sql);
$query->execute($params);
return $query;
}它将完成您的函数所做的一切,但是没有那么多代码,也没有不良的副作用。假设您将在一个循环中运行一个嵌套查询。在第二次查询执行之后,$this->_results变量是什么?在这样的函数中,不应该存在与特定查询相关的类变量.。
另外,
_error变量,因为它是非常无用的,而PDO本身的异常则更有用和更丰富execute()可以同时绑定所有参数。$params数组- execute()也会接受空数组。fetchAll() restult -您可以在以后再这样做,方法是将它像下面这样的$data = $db->query($sql, $params)->fetchAll();链接起来rowCount() -您可以一直只计算从fetchAll()返回的数组发布于 2016-08-29 10:58:41
您的预测是false,$value按值计算,因为bindParam需要&$变量,所以进行引用,尝试如下:
if(count($params)) {
foreach($params as $param => &$value) {
$this->_query->bindParam($param, $value);
}
}http://php.net/manual/en/pdostatement.bindparam.php
https://stackoverflow.com/questions/39204270
复制相似问题