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 Filtering Input for Queries Creating the Search Function

Igor Skoldin
Igor Skoldin
6,779 Points

Example code does not work

functions.php (the example code posted in teacher notes)

function search_catalog_array($search, $limit = null, $offset = 0) {
    include("connection.php");

    try {
       $sql = "SELECT media_id, title, category,img 
         FROM Media
         WHERE title LIKE ?
         ORDER BY 
         REPLACE(
           REPLACE(
              REPLACE(title,'The ',''),
              'An ',
              ''
           ),
           'A ',
           ''
         )";
       if (is_integer($limit)) {
          $results = $db->prepare($sql . " LIMIT ? OFFSET ?");
         $results->bindValue(1,"%".$search."%",PDO::PARAM_STR);
          $results->bindParam(2,$limit,PDO::PARAM_INT);
          $results->bindParam(3,$offset,PDO::PARAM_INT);
       } else {
         $results = $db->prepare($sql);
         $results->bindValue(1,"%".$search."%",PDO::PARAM_STR);
       }
       $results->execute();
    } catch (Exception $e) {
       echo "Unable to retrieved results";
       exit;
    }

    $catalog = $results->fetchAll();
    return $catalog;
}

Invoked in catalog.php:

if( ! empty($search) ) {
  $catalog = search_catalog_array($search, $items_per_page, $offset);
}

A call of search_catalog_array($search, $items_per_page, $offset); returns an empty array. If we do var_dump($search, $items_per_page, $offset), we will see string(4) "ring" int(8) int(0).

However, when we call directly search_catalog_array('ring', $items_per_page, $offset); it returns search results.

What is wrong?

Igor Skoldin
Igor Skoldin
6,779 Points

Fixed: it appeared that the problem was in the get_catalog_count function:

$result->bindValue(1, '%'.$search.'%', PDO::PARAM_STRING);

Instead of:

$result->bindValue(1, '%'.$search.'%', PDO::PARAM_STR);

so the whole thing worked well only when $search that was passed to get_catalog_count was null and was not used.