user882670
user882670

Reputation:

fetch(PDO::FETCH_ASSOC) return all values of a MySQL query into array

This query to MySQL:

SELECT `group_id`
            FROM `j30_user_usergroup_map`
            WHERE `user_id` =3065

Is returning the following results:

enter image description here

However, in PHP the following code:

$db = new PDO('mysql:host=localhost;dbname=', '', '');
    $sth = $db->prepare('SELECT `group_id`
        FROM `j30_user_usergroup_map`
        WHERE `user_id` =3065');
    $sth->execute();
    $result = $sth->fetch(PDO::FETCH_ASSOC);        
    print_r($result);

Is returning:

( [group_id] => 2 ) 

I want all the elements of the array, not just the 1st, as described here

Upvotes: 1

Views: 243

Answers (1)

rray
rray

Reputation: 2556

You have two way to solve this, change fetch() by fetchAll() or use an while and return a new array.

1) FetchAll approch

Change:

$result = $sth->fetch(PDO::FETCH_ASSOC);    

By:

 $result = $sth->fetchAll(PDO::FETCH_ASSOC);    

2) While approch

$items = array();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
   $items[] = $row;
}     

Upvotes: 1

Related Questions