php-oop中进行搜索?

kzipqqlq  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(331)

我有mysql数据库的产品id,p\ U名称(全文),国家,公司,价格。我需要在网站上进行动态搜索。现在我有这样的问题,当我查询的结果,我必须键入完全匹配的名称在数据库中。我试图放入%:query%,但执行时结果为空
型号:

public function getSearchResult($query){
        $params = [
            'query' => $query,
        ];
        // Prepare statement
        $search = $this->db->row("SELECT id, p_name FROM product WHERE p_name LIKE :query", $params);

        return $search;

        }

控制器:

public function indexAction(){

        $result = $this->model->getSearchResult($_POST['search']);

        $vars = [
            'result' => $result,
        ];
        $this->view->render('Search', $this->vars + $vars);
    }

db等级:

public function query($sql, $params = []){
        $stmt = $this->db->prepare($sql);
        if(!empty($params)){
            foreach ($params as $key => $val) {
                if (is_int($val)) {
                    $type = PDO::PARAM_INT;
                } else {
                    $type = PDO::PARAM_STR;
                }
                $stmt->bindValue(':'.$key, $val, $type);
            }
        }
        $stmt->execute();
        return $stmt;
    }

    public function row($sql, $params = []){
        $result = $this->query($sql, $params);
        return $result->fetchAll(PDO::FETCH_ASSOC);
    }
sxpgvts3

sxpgvts31#

您可以添加 % 在数组值中。更改型号代码如下:

public function getSearchResult($query){
        $params = [
            ':query' => '%'.$query.'%', // change this line
        ];
        // Prepare statement
        $search = $this->db->row("SELECT id, p_name FROM product WHERE p_name LIKE :query", $params);

        return $search;

        }

相关问题