【问题标题】:How to match the multiple selected options in the form to the database by query?如何通过查询将表单中多个选中的选项匹配到数据库中?
【发布时间】:2012-03-11 10:49:35
【问题描述】:

我为我的网站创建了一个商店搜索表单,用户可以在其中选择多个地区。 我想问在收到多选区选项后,如何返回用户多选选项的搜索结果?

例如用户可以选择US和JP,然后我的结果返回SHOP in US or JP

search.php

<select name="district" id="district">
<option value='US'>US</option>
<option value='UK'>UK</option>
<option value='JP'>JP</option> ... </select>

result.php
我知道要获得多个选择是通过使用:

foreach ($_GET['district'] as $selectedDistrict)
    $district[] = $selectedDistrict;

但是如何编写匹配查询?

比如SELECT * FROM shop WHERE district = '$district'?

【问题讨论】:

    标签: php html sql database option


    【解决方案1】:

    使用 IN。

    $in='"'.implode('","',$_GET['district']).'"';
    $where_part="WHERE district IN($in)"
    

    最终会得到这样的查询:

    SELECT * FROM shop WHERE district IN('JP','UK')
    

    【讨论】:

    • 感谢您的回答。但是,我不能在 implode 中使用 $_GET['district'] 来获得结果,而是使用以下建议并与您的 $district = '"'.implode('","',$districtArray) '"';现在,我成功了!谢谢!!!
    【解决方案2】:

    &lt;select name="district" id="district"&gt; 替换为&lt;select name="district[]" multiple="multiple" id="district"&gt;,然后试试这个

    <?php
    $districtArray=$_POST['district'];
    
       $sqlDistrictArray=join(',',$districtArray);  
    
       $findShopQuery="SELECT * FROM shops WHERE district IN ($sqlDistrictArray)";
      ?>
    

    【讨论】:

    • 您的建议很棒!然而,问题是查询必须是一个字符串,例如IN ('UK', 'JP'),但你的是 (UK,JP),所以无法准确得到结果。因此,我将您的答案与上述答案结合起来,并正确得出我的结果!谢谢你们两个!!
    • 当然,既然您发现这个答案很有帮助,那么您不妨点个赞。
    猜你喜欢
    • 2023-01-11
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2021-11-27
    相关资源
    最近更新 更多