PDO fetchAll not returning all rows

2.4k views Asked by At

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?

2

There are 2 answers

5
jeroen On BEST ANSWER

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.

2
Daedalus On

The return bit of your function stops execution of the function and returns the value. If you want to return both results of the queries you execute, you need to assign them to an array, and then return that:

public function getAllMultiple($username, $course) {
    $return = array(); //initialize the array before the foreach function
    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(); //collect the results
    }
    return $return; //return the array
}

Hopefully my comments are self-explanatory.