user1759941
user1759941

Reputation: 13

Array only returns last item, when using fetch

I am trying to return database result to an array. When using fetch it only returns the last item in the array.

If I write $result[$this->topic] .= $a instead of $result[$this->topic] = $a, the array returns all items but in only one string.

Function from my Database-class, with the while-loop:

        public function GetTopic($stmt) {

        if ($stmt->execute() == false) {
            throw new Exception($this->mysqli->error);
        }

        $stmt->bind_result($a); 
        $result = array();

        while ($stmt->fetch()) {
            $result[$this->topic] = $a;
        }

        $stmt->close();

        var_dump($result);
        return $result;
    }

Function from my Handler-class, where I call the function from the database-class:

        public function GetTopics() {

        $query = "SELECT Topic FROM question";
        $stmt = $this->db->Prepare($query);
        $result = $this->db->GetTopic($stmt);

        return $result;
    }

I´ve also tried using num_rows and store_result instead of fetch, which doesn´t work either. Any help is appreciated.

Upvotes: 1

Views: 121

Answers (1)

Alexey Sidorov
Alexey Sidorov

Reputation: 866

$result[$this->topic][] = $a;

Upvotes: 2

Related Questions