本文介绍了无法使用 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 从数据库返回正确的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!