Search code examples
phparrayspdofetchfetchall

PDO fetchAll not returning all rows


So I am trying to get multiple things from database. It is not working. In my functions file I have:

public function getAllMultiple($username, $course) {
        foreach ($course as $key) {
        $query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
        $query->bindValue(1, $username);
        $query->bindValue(2, $key['1']);
        try {
            $query->execute();
        } catch (PDOException $e) {
            die($e->getMessage());
        }
            return $query->fetchAll();
        }
}

In my feed function I have:

$array = $course->getAllAsMember($username);
print_r($course->getAllMultiple($username, $array);

I have two courses. I have a drug course and a class course. Unfortunately, it is only returning the drug course. Is there anything I'm doing wrong?


Solution

  • To expand on my comment, you can do something like:

    public function getAllMultiple($username, $course) {
        $query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
        $results = array();
        foreach ($course as $key) {
    
            $query->bindValue(1, $username);
            $query->bindValue(2, $key['1']);
            try {
                $query->execute();
            } catch (PDOException $e) {
                die($e->getMessage());
            }
            results[] = $query->fetchAll();
         }
        return $results;
    }
    

    You should also improve your error handling, for example by putting everything within a try - catch block instead of just a part of it.