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 CRUD Operations with PHP Reading and Writing Reports Filtering Data

How can i add optional parameters? I'm stuck on this exercise

Add an OPTIONAL parameter to accept if the function should return only people who have been Treehouse teachers. If the parameter is true, filter the results to show only the people that have the field 'treehouse' set to 1.

I don't know what to to here. it gives me error on fetch. Can somebody Help me?

index.php
<?php

function get_people($filter = null) {
    include 'connection.php';

    //add code here
  if($filter){
   try {
       $results = $db->query("SELECT * FROM people ORDER BY last_name DESC WHERE treehouse = 1");
    } catch(Exception $e) {
        echo "Error: Unable to retrieve query. " . $e->getMessage();
    }
  }


     return $results->fetchAll(PDO::FETCH_ASSOC);


}

1 Answer

Martin Balon
Martin Balon
43,651 Points

The problem is, that your try/catch block is inside the if statement. Function get_people has default argument 'null' which is passed to the if statement and therefore try/catch block is never run.

What I would do is:

first, put try/catch block out of the if statement

second, make the query string as variable $sql and delete WHERE clause. You can put this variable right after the comment '// add code here'. ($sql = SELECT * FROM people ORDER BY last_name DESC) Next pass this variable to your $result variable. ($results = $db->query($sql))

and last but not least, inside the if statement add WHERE clause to $sql variable - right before ORDER BY ($sql = SELECT * FROM people WHERE treehouse = 1 ORDER BY last_name DESC)

Martin Balon
Martin Balon
43,651 Points

And one more important thing - query inside the $sql variable should be wrapped in quotes :D