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 PHP & Databases with PDO PDO Queries & Results Query by ID

Maria De Bruyn
Maria De Bruyn
4,635 Points

Querying by ID

As I'm watching the Query by ID video, I am not getting the same results as the instructor, although I've checked to make sure the code is the same as his. Here is my code for films.php:

<?php

require_once('database.php');

try{
  $results = $db->query('select * from film where film_id = 201');

} catch(Exception $e){
  echo $e->getMessage();
  die();
}

 $film = $results->fetch(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">
  <title>PHP Data Objects</title>
  <link rel="stylesheet" href="style.css">

</head>

<body id="home">

  <h1>Sakila Sample Database</h1>

  <h2><?php echo $film['title']; ?></h2>



</body>

</html>

This is what shows up on my screen:

Sakila Sample Database

Film Title

The title is supposed to be replaced by an actual film title. It seems that the screen is just showing the index.php output, not the output for the file. Any help?

MOD: formatted quote

Maria De Bruyn
Maria De Bruyn
4,635 Points

This is the code for index.php:

<?php

require_once('database.php');

try{ $results = $db->query('select * from film');

} catch(Exception $e){ echo $e->getMessage(); die(); }

$films =$results->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8"> <title>PHP Data Objects</title> <link rel="stylesheet" href="style.css">

</head>

<body id="home">

<h1>Sakila Sample Database</h1>

<h2>Film Title</h2>

</body>

</html>

1 Answer

Maria De Bruyn
Maria De Bruyn
4,635 Points

Never mind, I figured it out. I had cut out this code from index.php, and I was only supposed to cut it out of films.php:

 <?php
    foreach($films as $film){
      echo '<li><i class="lens"></i><a href="films.php?
      id='.$film["film_id"].'">'.$film["title"].'</li>';
    }
?>
 </ol>

Now it works like a charm.

MOD: formatted code