我正在编写一个简单的类,并且有一个公共查询函数。除了结果和其他一些数据外,该函数还返回返回结果的行数。一切正常,但所有查询返回的计数都相同。
示例:
$db = DB::dbInstance();
$count1 = $db->query("SELECT * FROM users")->count(); // i.e. 10 records
$count2= $db->query("SELECT * FROM articles")->count(); // still 10 but they should not
正如您在上面的查询中看到的那样,两者都不同并且记录计数也不同,但对于不同的查询,返回的计数仍然相同。有解决方案吗?这是我的课堂片段:
<?php
class DB {
private static $_instance;
private $_pdo, $_query, $_results, $_count = 0, $_errors = false;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host=' . Config::info('mysql/host') . ';dbname=' . Config::info('mysql/dbname'), Config::info('mysql/dbuser'), Config::info('mysql/dbpass'));
} catch (PDOException $e) {
die('Failed connecting to database');
}
}
public static function dbInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql = NULL, $params = array()) {
$this->_errors = false;
if($this->_query = $this->_pdo->prepare($sql)) {
if(count($params)) {
$i = 1;
foreach($params AS $param) {
$this->_query->bindValue($i, $param);
$i++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_errors = true;
}
}
return $this;
}
public function count() {
return $this->_count;
}
}
?>
答案 0 :(得分:1)
将$this->_count 0;
行添加到查询函数的开头为我解决了这个问题。现在我的函数首先将计数设置为0,然后如果返回行,则更改值,否则返回0。正是我所期待的。
我的功能现在看起来像这样:
<?php
public function query($sql = NULL, $params = array()) {
$this->_errors = false;
$this->_count = 0;
if($this->_query = $this->_pdo->prepare($sql)) {
if(count($params)) {
$i = 1;
foreach($params AS $param) {
$this->_query->bindValue($i, $param);
$i++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_errors = true;
}
}
return $this;
}
?>