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 trialanil sirpal
4,091 PointsCRUD operations PHP optional parameters (whats wrong with my code)?
I'm getting 'Bummer , make sure last_name is ordered in descending order'
<?php
function get_people($filter = null) {
include 'connection.php';
//add code here
$where = '';
$sql = "SELECT * FROM people ORDER BY last_name DESC";
if ($filter) {
$where = " WHERE treehouse = 1";
}
try {
$results = $db->prepare($sql . $where);
$results->execute();
return $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
1 Answer
Chase Marchione
155,055 PointsHi Anil,
It looks like it has to do with the positioning of the WHERE clause (note: in pulling this off, I decided to remove the $where variable and its usage, and instead redeclared the $sql variable within the if statement):
<?php
function get_people($filter = null) {
include 'connection.php';
//add code here
$sql = "SELECT * FROM people ORDER BY last_name DESC";
if ($filter) {
$sql = "SELECT * FROM people WHERE treehouse = 1 ORDER BY last_name DESC";
}
try {
$results = $db->prepare($sql);
$results->execute();
return $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Hope this helps!
anil sirpal
4,091 Pointsanil sirpal
4,091 Pointscheers CJ