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 Using Relational Tables Fetching Many Relationships

Nathaniel Kolenberg
Nathaniel Kolenberg
12,836 Points

Not sure why answer is failing

Hi guys,

I'm not sure what I'm doing wrong - I would appreciate any help / suggestions you can provide!

Currently I've written the PHP code in index.php below. According to my understanding:

  1. I'm creating an array called 'genres' within the $item array.
  2. I'm looking at all elements I receive from the database and while I'm able to receive those (storing them in $row in the meantime), I do the following:
  3. Add onto the genres array another array (for each element I get from the PDO statement), for which the key is $row['genre_id'] and the value is $row['genre']

As far as I understand, this is what's requested in the challenge, but I'm clearly missing something. Could you please help me out?

Thanks in advance!

Nathaniel

index.php
<?php

include "helper.php";

$item["genres"] = [];
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
  $item["genres"][] = [$row["genre_id"]=>$row["genre"]];
}
/*
 * helper contains the following variables:
 * $item is an array that contains details about the library item
 * $results is a PDOstatement object with our genre results.
 */

3 Answers

Hi Nathaniel,

The issue is in your while loop, when you are assigning the values to the array. $item["genres"][] is creating a new entry in the array, but you already know what index ($row["genre_id"]) you want associated with what value ($row["genre"]). Instead of using blank brackets to push this key/value pair onto the array, place your key in the brackets and assign that to the value.

The proper way to add this key/value pair would be:

 while($row = $results->fetch(PDO::FETCH_ASSOC)) {
        $item["genres"][$row["genre_id"]] = $row["genre"];
 }
Nathaniel Kolenberg
Nathaniel Kolenberg
12,836 Points

Thanks a lot Lindsay - that makes sense :)

I also struggled with this one and came up with the same answer as Nathaniel Kolenberg. It would have been useful to see the explanation above in the course since Treehouse has taught me a certain syntax up until this point.