1

I can't find a way of finding the number of rows returned, after scouring the manual and other questions. How can I modify my fetchAll() method?

class Product {
    var $count;
    public function fetchAll(){
        $this->query = $this->pdo->prepare("SELECT * FROM $table");
        $this->query->setFetchMode( PDO::FETCH_ASSOC );
        $this->query->execute();
    }
    public function next(){
        $this->row = $this->query->fetch();
        if (!is_array($this->row)) return false;
        foreach ($this->row as $key => $val) {
            $this->{$key} = $val;
        }   
    }
    public function getCount(){
        return $this->count;
    }
}
2
  • $records = $stmt->fetchAll(PDO::FETCH_ASSOC); $num_rows = count($rows); voila, you're done. Commented Apr 11, 2014 at 10:02
  • Re your now deleted question, here's some possible things to try. Commented Apr 11, 2014 at 10:40

2 Answers 2

2

try $rows = $this->query->fetchAll(PDO::FETCH_ASSOC); return count($rows); after the $this->query->execute(); You can also use rowCount()

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I will use PDO's fetchAll() if I have to, but I'd prefer a PDO method. Sadly the manual says for rowCount() " returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement". (No SELECT)
@Jodes: rowCount() works fine for SELECT when using MySQL, try it and see.
If you count the number of records in the array after you're done selecting, you'll have that number. Why do people complicate simple things.. rowCount isn't always safe and in certain cases can return 0 when in reality you have rows that are > 0. Just count your array with records.
1

It depends on why do you need the count.

If you want to know how many products you have but not products themselves, then you have to run a distinct query.

If you want products, then you need no dedicated method for count at all.

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.