Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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