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 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.