0

Please, help, I'm stuck. I'm trying to make a query through PDO object in PHP with multiple LIKES Statements but something is not working. The same query works on Workbench with multiples words. This code works for one word as $search_term so I suspect that it has to be with having more than one LIKE statement, everything else, works just fine.

Also, I've trying moving the "%" wildcard concatenating inside the ´$results->bindParam($i, '%'.$word.'%', PDO::PARAM_STR );´ and removing from before. Also inside ´$query´ initiation.

The idea is when I search for get_products_subset(0,0,"pisode lones")should match "Episode II: Attack of the Clones".

The var_dump($result) at the end is

´object(PDOStatement)[3]
public 'queryString' => string '
            SELECT title, director, year
            FROM movies
            WHERE title LIKE ? OR title LIKE ?
            ORDER BY price
            LIMIT ?, ?' (length=210)´

Thanks a lot.

This is my code:

    ´<?php

    function get_products_subset($positionStart, $positionEnd, $search_term) {
        //Pagination
        $offset = $positionStart - 1;
        $rows = $positionEnd - $positionStart + 1;
        $list_of_words = preg_split('/\s+/',$search_term); //separate the keywords
        $numKeywords = count($list_words);//How many keywords are

        //Redacting the query using "? AND title LIKE ?"
        $likes = array();
        $i =0;
        while ( $i < $numKeywords) {
            $likes[] = "?";
            $i=$i+1;
        }
        $likePart = implode(' AND title LIKE ',$likes); //One phrase with all the question mark that I need

        $query = "
                    SELECT title, director, year
                    FROM products
                    WHERE title LIKE ".$likePart."
                    ORDER BY price
                    LIMIT ?, ?";

        require(ROOT_PATH . "inc/database.php");
        //$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME ,DB_USER,DB_PASS);

        try {
            $results = $db->prepare($query);

            //Replacing "?" for words.
            $i=0;
            foreach ($list_words as $word) {
                $i = $i + 1;
                $word = '%'.$word.'%';
                $results->bindParam($i, $word, PDO::PARAM_STR );
            }
            $results->bindParam($i+1, $offset, PDO::PARAM_INT );
            $results->bindParam($i+2, $rows, PDO::PARAM_INT );

            //execute
            $results->execute();
        } catch (Exception $e) {
            echo $e->getMessage();
            exit;
        }

        $subset = $results->fetchAll();
        return $subset;

    ?>´

0 Answers0