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

标签 php mysql pdo

我试图从数据库中的表返回行计数,但仍然得到错误的值。我需要行计数来处理分页的子集值。我的表中有 11 项,但我只返回 1 项并且不明白为什么:(

我的外部连接文件:

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 文件:

$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,它们用于两个不同的目的。

有人可以帮助我吗?

最佳答案

你应该更换

$rowCount = $query->rowCount();

$rowCount = $query->fetchColumn();

另外,看看FOUND_ROWS()

调用 fetch_num_rows 2 次是没有意义的,这样做就足够了:

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

关于php - 无法使用 php pdo 从数据库返回正确的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919265/

相关文章:

php - php cron 作业可以运行多长时间/我做得对吗?

php - Stripe API 帐户受到限制

mysql - 如何在 Sequel Pro 中编辑现有索引?

mysql - 拆分数据库表为经常查询的数据+其他数据

php - 如何在 ATTR_EMULATE_PREPARES 关闭时模拟 PDO 中的 DEFAULT 参数?

php - 为什么模拟准备好的语句失败并返回 Null?

php - Microsoft® ODBC Driver 11 for SQL Server® on RedHat Linux with PHP - 使用 PDO 为存储过程绑定(bind)参数时出错

php - 自动替换服务器端 mysql 数据库转储中的用户密码 (Laravel)

javascript - PHP 错误 : undefined variable

php - SQLSTATE[HY000] : General error: 1364 Field 'author_id' doesn't have a default value