带有多个LIKE语句的MySQL(PHP PDO)查询不起作用

时间:2015-09-02 04:26:31

标签: php mysql pdo

请帮忙,我被困住了。我试图通过PHP中的PDO对象进行多个LIKES语句查询,但有些东西不起作用。相同的查询在Workbench上使用多个单词。这段代码只能作为$ search_term用于一个单词,所以我怀疑它必须有多个LIKE语句,其他一切都可以正常工作。

另外,我试图在'$ results-> bindParam($ i,'%'。$ word。'%',PDO :: PARAM_STR)中移动“%”通配符连接;并从中删除之前。也在'$ query'启动内。

这个想法是我搜索get_products_subset(0,0,"pisode lones")时应该匹配“第二集:克隆人的攻击”。

最后的var_dump($result)

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

非常感谢。

这是我的代码:

    ´<?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 个答案:

没有答案