doushi3715 2013-11-12 01:29
浏览 85
已采纳

使用php pdo无法从数据库返回正确的行数

I am trying to return the row count from a table in my database but continue to get the wrong value. I need the row count to process subset values for pagination. There are 11 items in my table but I am only returning 1 and can't figure out why :(

My external connection file:

try {
    $pdo = new PDO('mysql:host=localhost;dbname=name', 'admin', 'password');

} catch (PDOException $e) {
    exit('Database error.');
}

My Article class:

class Article {

    public function fetch_all_articles($start, $max) {
        global $pdo;

        $query = $pdo->prepare("SELECT * FROM articles ORDER BY article_timestamp DESC LIMIT $start, $max");
        $query->execute();
        $articles = $query->fetchAll();
        $query->closeCursor();

        return $articles;
    }

    public function fetch_num_rows() {
        global $pdo;

        $query = $pdo->prepare("SELECT COUNT(*) FROM articles");
        $query->execute();
        $rowCount = $query->rowCount();
        $query->closeCursor();

        return $rowCount;
    }
}

And my index.php file:

$maxArticles = 4;                             //Show only 4 articles per page
$page = $_GET['page'] ? $_GET['page'] : 0;  //Get current page number or assign $page = 0 if no page number exists
$startRow = $page * $maxArticles;           //Get current article subset value                                          

$article = new Article;
$articles = $article->fetch_all_articles($startRow, $maxArticles);    //articles array
$numArticles = $article->fetch_num_rows();                          //number of articles
$rowCount = $article->fetch_num_rows();                             //number of articles

echo $rowCount;
echo $numArticles;

And yes I do need both $rowCount and $numArticles, they are being used for two different purposes.

Can anyone help me?

  • 写回答

2条回答 默认 最新

  • doudonglu3764 2013-11-12 01:34
    关注

    you should replace

    $rowCount = $query->rowCount();
    

    with

    $rowCount = $query->fetchColumn();
    

    also, take a look at FOUND_ROWS()

    there is no sense in calling fetch_num_rows 2 times, it is enough to do:

    $numArticles = $rowCount = $article->fetch_num_rows();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动