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

时间:2013-11-12 01:29:07

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

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

你应该替换

$rowCount = $query->rowCount();

$rowCount = $query->fetchColumn();

另外,请查看FOUND_ROWS()

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

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

答案 1 :(得分:1)

SELECT COUNT(*) FROM tableName只返回一行。该行中的数据是表中的行数。因此$query->rowCount()始终为1。如果您想要行数,则需要使用:

$query = $pdo->prepare("SELECT COUNT(*) ct FROM articles");
$query->execute();
$rowCount = $query->fetch(PDO::FETCH_OBJ)->ct;