2017-05-08 180 views
0

我想從基於複選框(列提供作爲複選框)的MySQL表中選擇列。以下是一個可重複的例子。MYSQL列選擇基於複選框和組複選框

<?php 
    require('connect.php'); 
?> 
<!DOCTYPE html> 

<head></head> 

<body> 
<div>  
    <form action="" method="POST"> 
     <input type="checkbox" name="check_list[]" value="ZONE"><label>ZONE</label> 
     <input type="checkbox" name="check_list[]" value="STATE"><label>STATE</label> 
     <input type="submit" name="submit" Value="Submit"/> 
    </form> 
</div> 

    <?php 
     if(isset($_POST['submit'])){ 
     if(!empty($_POST['check_list'])) { 
     $checkboxes = isset($_POST['check_list']) ? $_POST['check_list'] : array(); 
     foreach($checkboxes as $value) { 
      echo $value,','; //selected value 
     $sql = "SELECT $value,sum(RICEPDS) as 'CEREALS' from ck group by $value" ; 
     $result = mysqli_query($connection, $sql); 
     }}} 
     ?> 

    <div> 
     <table> 
     <thead> 
      <tr> 
       <?php 
        if (!$result) { 
         die("Query to show fields from table failed"); 
        } 
        $fields_num = mysqli_num_fields($result); 
         for($i=0; $i<$fields_num; $i++) 
         { 
          $field = mysqli_fetch_field($result); 
          echo "<th>{$field->name}</th>"; 
         } 
       ?> 
      </tr> 
     </thead> 
     <tbody> 
      <?php 
      while ($row = mysqli_fetch_assoc($result)) { 
      ?> 
      <tr> 
      <?php 
       foreach($row as $cell) 
        echo "<td>$cell</td>"; 
      ?> 
      </tr> 
      <?php 
      } 
      mysqli_free_result($result); 
      ?> 
     </tbody> 
    </table> 
    </div> 
</body> 
</html> 

可以理解當我選擇一個複選框時,表格會被返回。當我選中這兩個複選框時,我收到的錯誤消息是:die("Query to show fields from table failed");

我想我必須從$值得到最後的尾隨逗號。我該怎麼做?

+0

可以顯示什麼輸出中,你這個的print_r後得到($複選框) – Exprator

+0

這種問題是對症設計 – Strawberry

+0

使用mysqli_multi_query差的()函數 –

回答

1

從這個post我解決了這個問題,以啓發。我的工作代碼如下:

if(isset($_POST['submit'])){ 
     if(!empty($_POST['check_list'])) { 
      $my_values = implode(",", $_POST['check_list']); 
      $sql = "SELECT $my_values,sum(RICEPDS) as 'CEREALS' from ck group by $my_values" ; 
      $result = mysqli_query($connection, $sql); 
     }}