douyun1546 2013-04-20 18:36
浏览 51
已采纳

PHP中的多个Checkbox过滤器

I have been trying to figure this out for a while, but am not getting anywhere with it. I have read a lot of the other questions posted here and across the internet but am not being able to find a solution. Specially in the case of using multiple checkboxes.

Please bear with me as I try to explain the problem I am facing.

On a page I have a list of People with their corresponding location which i pull from a database using php/sql. What I am trying to achieve is to be able to filter the list according to location using checkboxes.

This is the code I have currently for the checkboxes.

<ul>
    <li><input type="checkbox" name="check_list[]" value="sydney">Sydney</li>
    <li><input type="checkbox" name="check_list[]" value="durban">Durban</li>
    <li><input type="checkbox" name="check_list[]" value="delhi">Delhi</li>
    <li><input type="checkbox" name="check_list[]" value="cairo">Cairo</li>
    <li><input type="checkbox" name="check_list[]" value="madrid">Madrid</li>
    <li><input type="submit"></li>
</ul>

This is the code I am using to check if a checkbox is checked and accordingly modify the SQL query

if (empty ($_POST['check_list'])) {

    $SQLquery = 'SELECT * FROM `people`';
    $query = $conn->query($SQLquery);

} elseif (!empty($_POST['check_list'])) {

    foreach($_POST['check_list'] as $check)

    $location = $check;

    $query = $conn->prepare('SELECT * FROM `people` WHERE `p_location` = :location');
    $query->execute(array('location' => $location));

}

Now this code works fine when only one checkbox is checked. However, when multiple checkboxes are checked this fails. It just shows nothing.

I know i can modify the SQL query using the OR operator to add other locations like so:

$query = $conn->prepare('SELECT * FROM `people` WHERE `p_location` = 'Delhi' OR `p_location` = 'Madrid')

However, I am unable to figure out how I can first check which all checkboxes are checked and then create the SQL statement in a way which will filter the results when there is more than one city selected.

I am also wondering if this is the best way to achieve something like this or not. I am open to alternative ways of achieving this within the scope of php/sql.

  • 写回答

3条回答 默认 最新

  • dpi96151 2013-04-20 18:43
    关注

    Untested, but should give you an idea of what you should do.

    ANSWER REVISED!

    $markers = str_repeat('?, ', count($_POST['check_list']) - 1) . '?';
    
    $query = $conn->prepare('SELECT * FROM `people` WHERE `p_location` IN (' . $markers . ')');
    $query->execute($_POST['check_list']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!