Row count with PDO

前端 未结 23 3167
春和景丽
春和景丽 2020-11-21 22:57

There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

23条回答
  •  既然无缘
    2020-11-21 23:17

    Answering this because I trapped myself with it by now knowing this and maybe it will be useful.

    Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach. For example:

    $query = "your_query_here";
    $STH = $DBH->prepare($query);
    $STH->execute();
    $rows = $STH->fetchAll();
    //all your results is in $rows array
    $STH->setFetchMode(PDO::FETCH_ASSOC);           
    if (count($rows) > 0) {             
        foreach ($rows as $row) {
            //output your rows
        }                       
    }
    

提交回复
热议问题