【问题标题】:searchfiltering across selections with php使用 php 对选择进行搜索过滤
【发布时间】:2013-03-09 09:42:56
【问题描述】:

我似乎无法找到正确的方法来创建一个搜索过滤函数,它将(正确的词?)一个扩展的 WHERE 语句推送到一个 SELECT 查询。

我有一段显示广告列表的代码:

    $where = isset($catid) ? ' AND ad.category = '.$catid.'' : '';

   $row = $db->dbh->query('SELECT ad.*, 
   (SELECT img.image FROM '.$config->db_prefix.'_images AS img 
   WHERE img.aid = ad.aid LIMIT 1) AS img 
   FROM '.$config->db_prefix.'_adverts ad 
   WHERE ad.approved = 1 '.$where.'');

假设我想查看特定类别 f.x 中的所有广告。电视(id 5),然后在该类别中显示给定价格范围(100 - 800)内的所有广告。 我不确定如何扩展我的 WHERE 语句来处理这个问题,以及我应该如何从我的 HTML 中做到这一点。 希望我的问题可以理解。

我在广告表中的数据库结构是这样的:

aid             int(11)     
fid             int(11)
ad_type         int(11)
title           varchar(255)
text            tinytext
price           decimal(10,2) 
category        int(11)
friends_allow   int(11)
cr_date         int(11)         
expiry_date     int(11)
approved        int(1)
ip              varchar(255)
email           varchar(255) 
zip_for_pickup  int(11) 
views           int(11)

解决方案

$filters = array();

if(!empty($post_fields['cat']) && $post_fields["cat"] != "all") {
        $category = $post_fields['cat'];
        $filters[] = '(category = ' . $category .')';
    }

if(!empty($post_fields['search_field'])) {
    $title_and_text = $post_fields['search_field'];
    $filters[] = '(title LIKE "%' . $title_and_text  .'%" OR text LIKE "%' . $title_and_text .'%")';
}

if(!empty($post_fields['price_min_field'])) {
    if(!empty($post_fields['price_max_field'])) {
        $filters[] = '(price >= '. $post_fields['price_min_field'].' AND price <= '. $post_fields['price_max_field'] .')';
    } else {
        $filters[] = '(price >= '. $post_fields['price_min_field'].')';
    }      
}

if(!empty($post_fields['distance'])) {
    $adverts = new Adverts();
    $filters[] = '('. $adverts->find_geo_location($post_fields["userzip"], $post_fields["distance"]) .')';
}

$filter =  implode(' AND ', $filters); 

【问题讨论】:

  • 你想让我们猜测你的数据库的结构吗?
  • 对不起!问题随结构更新。

标签: php html mysql sql select


【解决方案1】:

在 HTML 中放置 2 个下拉菜单 Price From 和 Price To。 在 PHP 端获取选中的值。基于该使用连接。用选定的值替换 100 和 800。

 $where = isset($catid) ? ' AND ad.category = '.$catid.'' : '';

 if ($pricefilter) {
   $where .= 'AND ad.price>100 AND ad.price < 800';
 }

【讨论】:

  • 如果我使用搜索框并找到带有text LIKE "%'. $search_string .'%" OR title LIKE "%'. $search_string .'%" 的结果列表,然后在该结果中再次想要使用价格范围进行过滤 - 那是我的问题
  • 在某些时候您可能需要修改您的查询。您必须保留先前选择的选项。您必须根据过滤器选择计划“$where”部分。
猜你喜欢
  • 2012-10-23
  • 2021-08-20
  • 1970-01-01
  • 2021-01-06
  • 2019-07-14
  • 2019-04-25
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
相关资源
最近更新 更多