如何在数据库中选择所有选中的多个选择在php?

时间:2018-03-10 06:47:32

标签: php html mysql pdo

这是我的流程



  $sec_id = implode(', ', $_POST['sec_id']);

  $stmtSec = $crud->runQuery("SELECT * FROM tbl_section WHERE sec_id IN (':sec_id')");
  $stmtSec->execute(array(":sec_id" => $sec_id));
  while ($rowSec = $stmtSec->fetch(PDO::FETCH_ASSOC))
  {
     $section[] = $rowSec['section'];
  }




但是没有任何内容可以使用我的代码。

这是我的多选代码。



                      <select name="sec_id[]" data-live-search="true" class="selectpicker form-control border-input" style="text-align-last:center;" title="Select Section" required multiple>
                        <?php
                        $stmtSection = $crud->runQuery('SELECT * FROM tbl_section ORDER BY sec_id DESC');
                        $stmtSection->execute();
                        while($rowSection=$stmtSection->fetch(PDO::FETCH_ASSOC))
                        {
                          print("<option value='".$rowSection['sec_id']."'>".$rowSection['section']."</option>");
                        }
                        ?>
</select>
&#13;
&#13;
&#13;

还有另一种在数据库中选择多个的方法吗?还是查询? 请帮忙。

1 个答案:

答案 0 :(得分:1)

这里我已经包含并更新了代码。

    $sec_id = implode(', ', $_POST['sec_id']);
    $stmtSec = $crud->runQuery("SELECT * FROM tbl_section WHERE sec_id IN (':sec_id')");
    $stmtSec->execute(array(":sec_id" => $sec_id));
    while ($rowSec = $stmtSec->fetch(PDO::FETCH_ASSOC)) {
       $section[] = $rowSec['sec_id'];
    }
    $stmtSection = $crud->runQuery('SELECT * FROM tbl_section ORDER BY sec_id DESC');
    $stmtSection->execute();
    while($rowSection=$stmtSection->fetch(PDO::FETCH_ASSOC))
    {
        $optionsSelected = in_array($rowSection['sec_id'], $section) ? 'selected="selected"' : '';
        print("<option'" . $optionsSelected . "'value='".$rowSection['sec_id']."'>".$rowSection['section']."</option>");
    }