我对这个问题感到困惑已经好几个小时了。我有使用 PDO 访问 Sybase 数据库的 PHP 代码。问题是 rowCount()
的函数始终不断返回 -1
的值。我在这里找到了解决方案PDO::rowCount() 返回 -1,用户在准备查询时提供 PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL
参数。该解决方案对他有用,但出于某种原因不适合我。如果你们能在这方面帮助我,请表示感谢。
这是我的代码:
public function query($sql, $params = array()){
$this->_error = false; //always first initialize to false
if( $this->_query = $this->_pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)) ){
$x = 1;
if( count($params) ){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if( $this->_query->execute() ){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
echo $this->_count = $this->_query->rowCount(); //this line returns -1
} else {
$this->_error = true;
}
}
return $this;
}
我将使用如下方式调用此函数:
$data = $this->_db->query( "SELECT username FROM users WHERE username=?", array($user) );
谢谢。
我发布了我自己的解决方案,以便它可以帮助可能遇到相同问题的人。所以我按照其他人的解决方案首先计算返回的行,然后如果行数大于零,我们继续执行。我的代码如下:
$sql = "SOME SQL STATEMENT HERE";
if( $this->_query = $this->_pdo->prepare( "SELECT COUNT(*) as computedRow FROM ( {$sql} ) AS X", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL) ) ){
$x = 1;
if( count($params) ){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if( $this->_query->execute() ){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
foreach ($this->_results as $obj){
$this->_count = $obj->computedRow;
}
if($this->_count){
if( $this->_query = $this->_pdo->prepare( $sql . $orderby , array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL) ) ){
$x = 1;
if( count($params) ){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if( $this->_query->execute() ){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}
else {
$this->_error = true;
}
}
}
else{
$this->_count = 0;
}
}
else {
$this->_error = true;
}
}
希望这可以帮助那里的某人。享受:)