无法使用php pdo从数据库返回正确的行数 [英] Can't return correct row count from database using php pdo

查看:82
本文介绍了无法使用php pdo从数据库返回正确的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库中的表返回行数,但继续获取错误的值.我需要行计数来处理用于分页的子集值.我的表中有11个项目,但我只返回1,无法弄清楚为什么:(

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 :(

我的外部连接文件:

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

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

我的文章课:

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;
    }
}

还有我的index.php文件:

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;

是的,我确实需要$ rowCount和$ numArticles,它们分别用于两个不同的目的.

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

有人可以帮助我吗?

推荐答案

您应该替换

$rowCount = $query->rowCount();

使用

$rowCount = $query->fetchColumn();

另外,请查看 FOUND_ROWS( )

调用fetch_num_rows 2次是没有意义的,足以做到这一点:

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

$numArticles = $rowCount = $article->fetch_num_rows();

这篇关于无法使用php pdo从数据库返回正确的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆