适用于相同列的条件两次或三次

时间:2014-06-20 06:07:27

标签: php jquery ajax

我有一个产品目录页面,通过ajax显示产品。 Ajax调用的代码如下:

function updateProducts(opts){

    $.ajax({
      type: "POST",
      url: "func.php",
      dataType : 'json',
      cache: false,
      data: {filterOpts: opts},
      success: function(records){
        $('#slider').html(makeProdiv(records));

      }
    });
  }

和func.php的代码如下:

$pdo = new PDO('mysql:host=localhost;dbname=filter', 'root', '');

  $select = 'SELECT id, pname, prate, pdesc';
  $from = ' FROM product';
  $where = ' WHERE TRUE';

  $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

  if (in_array("Shoes", $opts)) { $where .= " AND ptype = 'Shoes'"; }
  if (in_array("Belt", $opts))  { $where .= " AND ptype = 'Belt'"; }
  if (in_array("lt1th", $opts)) { $where .= " AND prate < 1000"; }
  if (in_array("mr1th", $opts)) { $where .= " AND prate > 1000"; }
  if (in_array("lth", $opts))   { $where .= " order by prate asc"; }
  if (in_array("htl", $opts))   { $where .= " order by prate desc"; }

  $sql = $select . $from . $where;
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $results = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($results);
  echo($json);

我面临的问题是:

  1. 当我在过滤器中同时选择“腰带”和“鞋子”时,没有显示任何结果,因为在选择这两个选项时查询结果如下:
  2. SELECT id, pname, prate, pdesc FROM product WHERE TRUE AND ptype = 'Shoes' AND ptype = 'Belt'

    请告诉我如何实现这一点,因为单品检查工作正常。

3 个答案:

答案 0 :(得分:1)

嘿谢谢你的所有回复

我想出来并实现如下:

$allptype = array('Belt','Shoes');
$selectedptype = array();
  foreach($allptype as $ptype){
    if(in_array($ptype,$opts)){
        $selectedptype[] = $ptype;
    }
  }
  if(count($selectedptype)){
    $where .= " AND ptype IN ('".implode("', '", $selectedptype)."')";
  }

对我来说似乎是好事。如果sombody有另一种方法,请随时发布。

答案 1 :(得分:0)

if(in_array(&#34; Shoes&#34;,$ opts)){$ where。=&#34; AND ptype =&#39; Shoes&#39;&#34 ;; }   if(in_array(&#34; Belt&#34;,$ opts)){$ where。=&#34; AND ptype =&#39;腰带&#39;&#34 ;; }

为什么你没有使用&#39;或&#39;代替? 所以完整的sql就像

&#34; SELECT id,pname,prate,pdesc FROM product WHERE TRUE AND ptype =&#39; Shoes&#39; AND ptype =&#39;腰带&#39;&#34; 这就是你想要的吗?

答案 2 :(得分:0)

TRUE子句中删除WHERE

您的ptype值在任何时候都不会相同(如果是shoesbelts则表示

所以你查询需要像这样改变,

$pdo = new PDO('mysql:host=localhost;dbname=filter', 'root', '');

  $select = 'SELECT id, pname, prate, pdesc';
  $from   = ' FROM product';
  $where  = ' WHERE';

  $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

  if (in_array("Shoes", $opts) && in_array("Belt", $opts)) { 
     $where .= " ptype = 'Shoes' OR ptype = 'Belt'"; 
  }
  else if (in_array("Shoes", $opts)) { 
     $where .= " ptype = 'Shoes'"; 
  }
  else if (in_array("Belt", $opts))  { 
     $where .= " ptype = 'Belt'"; 
  }

  $sql = $select . $from . $where;
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $results = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($results);
  echo($json);
相关问题