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 Querying Multiple Tables with JOIN

janeporter
PLUS
janeporter
Courses Plus Student 23,471 Points

getting an error "Unable to retrieve data" when I include media_id in the query

here is my code in function.php

function single_item_array($id) {
  include("connection.php");

  try {
    $results = $db->query("SELECT media_id, title, category, img, format, year, genre, publisher, isbn 
                           FROM media
                           JOIN genres ON media.genre_id = genres.genre_id
                           LEFT OUTER JOIN books ON media.media_id = books.media_id
                           WHERE media.media_id = $id");
  } catch (Exception $e) {
    echo "Unable to retrieve results";
    exit;
  }

  $catalog = $results->fetch(PDO::FETCH_ASSOC);
  return $catalog;
}

var_dump(single_item_array(1));

when I preview in the browser I get "Unable to retrieve results", but when I remove media_id from the query, it works fine...

What could be the issue here?

Hey Janeporter, As you know you are using join here on books and genres table. Here in our database we have media_id in 2 tables i.e. media and books table so in query you must specify the table from which you are capturing media_id.If you are fetching it from media table then you have to write something like media.media_id & in case of books books.media_id.

I hope you understand