Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Integrating PHP with Databases Querying the Database with PHP Working with Results

Henry Lin
Henry Lin
11,636 Points

fetchAll() vs fetchAll( PDO::FETCH_ASSOC )

In the previous videos, Alena demonstrated the differences between fetchAll() with default style and PDO::FETCH_ASSOC style. She said that PDO::FETCH_ASSOC would remove all the numeric keys and only leave with associated keys. However, in this challenge, I thought we need do something like this:

//get the associate array with proper keys
$new_arr = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($new_arr as $item ){
//call send_offer
send_offer($item['mail_id'].....)
}

but this code doesn't work. And I have checked the answer. Instead of

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

We need

$new_arr = $result->fetchAll();

Why is this???

index.php
<?php
include "helper.php";

try {
    $results = $db->query(
        "SELECT member_id, email, fullname, level FROM members"
    );
} catch (Exception $e) {
    echo $e->getMessage();
}
//add code below this line

1 Answer

Steven Snary
Steven Snary
17,540 Points

You were on the right track with your initial thinking using FETCH_ASSOC...

You will have access to the $results array -> I think you may have typed in the incorrect column name, instead of

$item['mail_id']...

you should have used

$item['member_id']...

SPOILER ALERT -> the following loop works for this challenge

foreach ($results as $result) {
  send_offer($result[member_id], $result[email], $result[fullname], $result[level]);
}