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

Qasim Hafeez
Qasim Hafeez
12,731 Points

Search not working (SQL syntax error)

My search is not working. Here is the error message when I type in the word 'hello':

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '%hello%' ORDER BY REPLACE(REPLACE(REPLACE(title, 'The ',''),'An ',' at line 3

The $search variable is obviously being set but, something else is going wrong and I can't figure it out. Here is my search function

function search_catalog_array($search, $limit=null, $offset=0){

    try {
        $sql = "SELECT Media.media_id, title, category, img 
                FROM Media
                WHERE title LIKE = ?
                ORDER BY 
                REPLACE(REPLACE(REPLACE(title, 'The ',''),'An ',''),'A ','')";

                        $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);

    } catch(Exception $e){
        echo $e->getMessage();
    $catalog = $results->fetchAll();
    return $catalog;

Can anybody figure it out?

1 Answer

Qasim Hafeez
Qasim Hafeez
12,731 Points

I figured it out. I wrote "LIKE = ?" instead of "LIKE ?"