【问题标题】:Multiple option search from database using single query使用单个查询从数据库中搜索多个选项
【发布时间】:2017-05-26 05:46:28
【问题描述】:
$data1=$_REQUEST['data1'];
$data2=$_REQUEST['data2'];
$data3=$_REQUEST['data3'];

mysqli_query($conn,"SELECT pu.id, monthname(pu.date_complete) AS Month 
       FROM `pds_user` pu 
     WHERE monthname(pu.date_complete) IN ('".implode("','",$data1)."') 
     AND pu.date_complete IN ('".implode("','",$data2)."') 
     AND Name IN ('".implode("','",$data3)."')
     ORDER BY Month");

如果$data1为空,怎么办?

【问题讨论】:

  • 检查 !empty() 然后创建动态 where 子句
  • 如何创建动态where子句?
  • @Smritimay Debnath 从$data 获取数据,如果这是空的......你可以使用PHP empty() 函数
  • 实际上,如果 $data1 为空,那么我想要完整的表数据.. 有可能吗?

标签: php jquery mysqli


【解决方案1】:

使用!empty然后创建动态where clause

    $where_clause ='where 1=1';

    if(!empty($data1))
    {
       $where_clause .= " And monthname(pu.date_complete) IN ('".implode("','",$data1)."')"; 
    }

    if(!empty($data2))
    {
       $where_clause .= " And pu.date_complete IN ('".implode("','",$data2)."') "; 
    }

    if(!empty($data3))
    {
       $where_clause .= " And Name IN ('".implode("','",$data3)."')"; 
    }

    mysqli_query($conn,"SELECT pu.id, monthname(pu.date_complete) AS Month 
                    FROM `pds_user` pu $where_clause  ORDER BY Month");

【讨论】:

  • 谢谢它对我有用。请分别更改语法 if(!empty($data1)) $data2, $data3 ...
  • 哦,不错,很高兴能帮助你@SmritimayDebnath
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多