0

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 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

SELECT COUNT(*) FROM tableName just returns a single row. The data in that row is the number of rows in the table. So $query->rowCount() will always be 1. If you want the number of rows, you need to use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.