选中复选框时如何返回所有查询?

时间:2016-05-26 09:52:25

标签: php mysqli

当我选中checkbox或mulitple复选框时,它只返回我的数据库数据的一行,如何显示数据库中的所有数据?

<?php foreach($portControllerClass->getAllAgencies() as $port_list){ ?>
    <input type="checkbox" name="port[]" value="<?=$port_list['agencies']?>"> <?=$port_list['agencies'] . '</br>'; 
} ?>

$date_from = date('Y-m-d', strtotime($_POST['date_from']));
$date_to = date('Y-m-d', strtotime($_POST['date_to']));

foreach($_POST['port'] as $port){ 

   $sql = "SELECT @a:=@a+1 no, letter_no, letter_date, conformity_date,
                  agencies, DATEDIFF(`conformity_date`,`letter_date`) AS DiffDate 
           FROM info_lab, (SELECT @a:= 0) AS a 
           WHERE agencies LIKE '%". implode(",",$_POST['port']) ."%' 
            and conformity_date BETWEEN '".$date_from."' 
            and '".$date_to."'";

   $query = $con->query($sql);
   $row = $query->fetch_array();
   echo $row['letter_no'];
}

2 个答案:

答案 0 :(得分:0)

不要在查询中使用$ _POST ['port'],而是使用$ port。

所以你的查询将成为:

$sql = "SELECT @a:=@a+1 no, letter_no, letter_date, conformity_date,
              agencies, DATEDIFF(`conformity_date`,`letter_date`) AS DiffDate 
       FROM info_lab, (SELECT @a:= 0) AS a 
       WHERE agencies LIKE '%".$port."%' 
        and conformity_date BETWEEN '".$date_from."' 
        and '".$date_to."'";

如果每个数据都有多行,那么在$ query = $ con&gt; query($ sql)之后添加这段代码;

if ($query->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo $row['letter_no'];
    }
} else {
    echo "0 results";
}

答案 1 :(得分:0)

您只有一个输入复选框,因此您只能获得一个值。为了获得多个值,我认为你应该使用foreach循环与数据库中的复选框值,如下所示:

foreach ($port_list['agencies'] as $value){
 <input type="checkbox" name="port[]" value="<?php echo $port_list['agencies']?>"> <php echo $port_list['agencies'] . '</br>'; ?>    
}

另外,请不要使用<?=代码,因为它已弃用,请改用<?php ?>