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

Devin Gray
Devin Gray
39,261 Points

Filtering Data with PHP: Why is this wrong?

https://teamtreehouse.com/library/crud-operations-with-php/reading-and-writing-reports/filtering-data

I've tried multiple different combinations trying to get this function to work and I want to know why it is wrong? And the error I get keeps saying to make sure last_name is ordered in descending order, which it is.

Any ideas?

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

    //add code here
  $sql = "SELECT * FROM people ORDER BY last_name DESC";
  $where = '';
  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();
  }
}
index.php
<?php
function get_people($filter = null) {
    include 'connection.php';

    //add code here
  $sql = "SELECT * FROM people ORDER BY last_name DESC";
  $where = '';
  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();
  }
}

2 Answers

Peter Hatzer
Peter Hatzer
20,837 Points

Hi Devin,

Your where clause should be before the order by.

Example

<?php

$where = '';

if ($filter) {
   $where = "WHERE treehouse = 1";
 }

$sql = "SELECT * FROM people ".$where."   ORDER BY last_name DESC";

//Or you could do it this way either

$sql = "SELECT * FROM people " ;

if ($filter) {
   $sql .= "WHERE treehouse = 1";
 }
$sql .= " ORDER BY last_name DESC";

Then just call the $sql

Devin Gray
Devin Gray
39,261 Points

Honestly, I just removed the $where altogether and just concatenated the if statement on to the $sql variable and it said my answer was correct. Weird. So I basically did your second option. But thanks for the help :)

Peter Hatzer
Peter Hatzer
20,837 Points

No problem, keep on coding :)