PDO::rowCount() returning -1

允我心安 提交于 2019-12-22 12:32:18

问题


i have this function below. that i used to run on a MySQL DB. I had to move to a SQL Server 2008, easy thing.

But, after that, the rowCount() keeps returning -1, I've never had this happen before. I'm sure that my SQL query is returning the results, because if I do a print_r() on my return (the $rows var), everything gets printed.

So, if anyone had this issue, please help me to figure this out.

Sorry for any grammatical mistake.

public function listar(){

    $retorno = array();

    $sql = "SELECT m.id, m.descricao, m.link, m.categoria, m.icone FROM menus AS m,    grupos AS g, permissoes AS p WHERE (g.id = p.idgrupo AND m.id = p.idmenu) AND (p.status = :pstatus AND g.status = :gstatus AND m.status = :mstatus) AND g.id = :gid ORDER BY m.ordem ;";

    $vars = array(":pstatus"=>1,":gstatus"=>1,":mstatus"=>1,":gid"=>$_SESSION['group']);

    $stmt = $this->pdo->prepare($sql);

    foreach($vars as $index => $value){
        $stmt->bindValue($index,$value);
    }

    if($stmt->execute()){
        $count = $stmt->rowCount();
        $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        $rows['msg'] = '1';
        $rows['length'] = $count;

        $i = 0;
        while($i < $count){
            foreach($rows[$i] as $index => $value){
                $rows[$i]->$index = utf8_encode($value);
            }
            $i++;
        }

        return $rows;
    } else {
        return array("msg" => '0');
    }

}

回答1:


Got it guys.

The prepare() statement should receive one more parameter. array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL) .

$stmt = $this->pdo->prepare($sql,array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

After that the rowCount() should work fine.

Thanks for the answer @Rasclatt.




回答2:


I think you may be running into the gotcha on the PDO rowCount() function. As stated in the PHP manual. The second sentence is the gotcha...:

"If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications."

Instead, you should use a COUNT(*) sql statement.



来源:https://stackoverflow.com/questions/27363413/pdorowcount-returning-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!