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 Using a Prepared Statement

Sean Maloney
PLUS
Sean Maloney
Courses Plus Student 3,824 Points

Why isn't this code working?

It's telling me to add a where clause to select a single member_id.......

index.php
<?php
function get_member($id) {
    include("connection.php");

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

    $member = $results->fetch();
    return $member;
}

2 Answers

Vehbi Oztomurcuk
Vehbi Oztomurcuk
4,283 Points

you should use place holders and prepare method, this should pass all three tasks;

function get_member($member_id) {
    include("connection.php");

    try {
      $results = $db->prepare(
          "SELECT member_id, email, fullname, level
          FROM members
          WHERE member_id = ?"
      );

$results->bindParam(1,$member_id,PDO::PARAM_INT);
$results->execute();

    } catch (Exception $e) {
      echo "bad query";
    }

    $members = $results->fetchAll();
    return $members;
}
Sean Maloney
Sean Maloney
Courses Plus Student 3,824 Points

Thanks, that did work, but I think it might of been because I changed $results->fetchAll(); to $results->fetch(); and you didn't. I had tried the prepare method and that failed as well

Vehbi Oztomurcuk
Vehbi Oztomurcuk
4,283 Points

fetch(); is just fine as well with the first task, but it requires fetchAll(); for 2nd and 3rd tasks, workspaces can be tricky sometimes, as long as you understand the structure more or less it doesn't matter I guess. have fun.