doujinge9648 2018-01-24 22:10
浏览 66
已采纳

WHERE / AND中是否有条件查询返回所有值的值,如果值在表单中保留为空,或者是否为所选值?

This seems simple but I cannot find a good answer anywhere. I am trying to pass several variables from a form, and some the user might decide do not pertain so they can leave blank, in which case no value is passed to the results page (such as name being left blank so the name value posted is ""

On the results page, I want to run a query that returns all results for a field that is left blank on the search form.

So if someone chooses NY for state and leaves name blank, I want my query to return all names for people in NY since they choose NY for State but left in the form but left Name blank.

I need a condition inside the where clause that inserts the selected name value if selected or else if was left blank on form returns all values for that variable that meet the AND criteria.

 //Get variables from form page (and they left name blank/no value so name="")
 $name = $_GET['name'];
 $state = $_GET['state'];

 $query = "
(SELECT * 
   FROM schools 
  where name= **HOW GET ALL RESULTS IF VALUE
 WAS BLANK OR ELSE USE THE SELECTED VALUE IF SELECTED?** 
    and city='$city')";
  • 写回答

1条回答 默认 最新

  • doucheng9634 2018-01-24 22:35
    关注

    Try this

    $query = "(
        SELECT * 
        FROM schools 
        WHERE ($name IS NULL OR $name = '' OR name = $name)
            AND city='$city')";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数