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

Logan Fox
PLUS
Logan Fox
Courses Plus Student 3,379 Points

I am not sure what I am doing wrong in this code challenge

Can someone help me?

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

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

foreach($results as $id => $value) { 
  $member_id = $value['member_id'];
  $email = $value['email'];
  $fullname = $value['fullname'];
  $level = $value['level'];
}
//add code below this line

2 Answers

OK, I'm editing the answer with the full working code.

Let's go through this step by step. Do you remember in the video when Alena told us that the fetchAll function returns a multi-dimensional array? This means that $example_array will come up like this:

array(3)  { 
     [0]=> array(8)  { 
         ["member_id"]=> string(1) "1" 
         [0]=> string(1) "1" 
         ["email"]=> string(23) "randy@teamtreehouse.com" 
         [1]=> string(23) "randy@teamtreehouse.com" 
         ["fullname"]=> string(10) "Randy Hoyt" 
         [2]=> string(10) "Randy Hoyt" 
         ["level"]=> string(6) "bronze" 
         [3]=> string(6) "bronze" 
     } 

This means that when you specify the foreach loop to get both the $id and $value, the $id will retrieve the keys for the internal arrays and $value will retrieve the arrays inside; thus, in the context of this video, retrieving $id is meaningless. So, if you want to loop through the properties of member_id, email, and so on, you have to specify those in $value like this:

$value["member_id"]

I highly recommend you to explore the arrays and stuff using var_dump to get a better understanding.


Full Code:

<?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
$example_array = $results->fetchAll();

foreach ($example_array as $value) {
  send_offer($value["member_id"], $value["email"], $value["fullname"], $value["level"]);
}  
Logan Fox
Logan Fox
Courses Plus Student 3,379 Points

ok I did that but it is saying the same thing: Bummer! You need to pass all 4 arguments: member_id, email, fullname, level