pdo高级搜索查询构建问题

时间:2015-01-19 16:37:57

标签: php mysql pdo prepared-statement advanced-search

我正在尝试进行高级搜索,我有这个工作,但我正在对每个获取变量进行完整查询,这不好但是有效

现在我正在尝试构建查询,具体取决于url变量是否为空。但我无法弄清楚为什么这不起作用。查询工作正如我测试过的那样,我没有正确构建查询吗?

这是函数

public function search($man, $mod, $min, $max)
    {
        $this->currentLocation();
        $bind = '';

        $query .= 'SELECT listed_watches.*, watch.*, watch_images.* FROM listed_watches';

        $query .= 'LEFT JOIN watch ON watch.Id = listed_watches.watchID';

        $query .= 'LEFT JOIN watch_images ON listed_watches.url = watch_images.url';

        $query .= 'WHERE listed_watches.sellto REGEXP :search';

        if(!empty($man)){
            $query .= 'AND listed_watches.manufacture = :man';
            $bind  .= "$smt->bindValue(':man', $man);";
        }

        if(!empty($mod)){
            $query .= 'AND listed_watches.model = :mod';
            $bind  .= "$smt->bindValue(':mod', $mod);";
        }

        if(!empty($min)){
            $query .= 'AND listed_watches.minPrice > :min';
            $bind  .= "$smt->bindValue(':min', $min);";
        }

        if(!empty($max)){
            $query .= 'AND listed_watches.maxPrice < :max';
            $bind  .= "$smt->bindValue(':max', $max);";
        }

        $query .= 'GROUP BY listed_watches.id';

        $smt = $this->pdo->prepare(''.$query.'');

        $smt->bindValue(':search', "^[".$this->userLocation."]");
        $bind;
        return $smt->fetchAll();

    }

当我搜索并输入时选择$ man和$ mon我会收到此错误

Undefined variable: smt 
Trying to get property of non-object in

此错误是对此行的裁判

$bind  .= "$smt->bindValue(':mod', $mod);";

1 个答案:

答案 0 :(得分:0)

首先你需要创建$ smt对象,然后就可以使用它了。

    if(!empty($man)){
        $query .= 'AND listed_watches.manufacture = :man';
    }
    if(!empty($mod)){
        $query .= 'AND listed_watches.model = :mod';
    }

    // ...

    $query .= 'GROUP BY listed_watches.id';

    $smt = $this->pdo->prepare(''.$query.'');

    $smt->bindValue(':search', "^[".$this->userLocation."]");

    if(!empty($man)){
        $smt->bindValue(':man', $man);
    }
    if(!empty($mod)){
        $smt->bindValue(':mod', $mod);
    }