2016-09-16 81 views
0

我有5个月的php和mysql工作经验。我的问题是如何在复选框中选择我的mysql数据库表中的某些列,并在php的html表格中显示那些选定列的数据? 请参阅下面的代码并帮我解决这个问题。选择mysql列与复选框,并在html表中显示数据,php

复选框代码:

<form role="form" id="viewallteachers" method="POST" autocomplete="on" action=""> 
        <h4>Kindly check the items to view in the table. You have a maximum of 10 items to view at a time in the table.</h4> 
        <hr> 
        <div class="row"> 
         <div class="col-sm-4"> 
          <div class="checkbox"> 
           <label> 
            <input type="checkbox" name="check_list[]" value="tpicture">Picture 
           </label> 
          </div> 
          <div class="checkbox"> 
           <label> 
            <input type="checkbox" name="check_list[]" value="teacherID">Teacher ID 
           </label> 
          </div> 
          <div class="checkbox"> 
           <label> 
            <input type="checkbox" name="check_list[]" value="staffID"> 
            Staff ID 
           </label> 
          </div> 
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
        <button type="submit" name="btnshowcolumns" class="btn btn-primary">Save changes</button> 
        </form> 

现在下面是我的表显示每个选择的列选择的列和数据的代码。

<?php if(!empty($_POST['check_list'])) { 
$check_list = $_POST['check_list']; 
$counter = count($check_list); 
for($x=0; $x<=$counter; $x++){ 
    if(!empty($check_list[$x])){ 
    $sql = "SELECT `".$check_list[$x]."` FROM teachers"; 
$db = new PDO('mysql:host=localhost:3306;dbname=gnoc_db', 'root', 'xxxx'); 
     $select = $db->prepare($sql); 
     $select->execute(); 
     while($row = $select->fetch(PDO::FETCH_ASSOC)) { 
     echo '<tr>'; 
     foreach ($row as $key=>$value) { 
      echo '<td>'.$key . ' = ' . $value .'</td>'; 
       } 
       echo '</tr>'; 
       } /* END OF IF */ 
       } /* END OF FOR LOOP */ 
     } 
    } 
?> 
</tbody> 
</table> 

以下是在图像: image of checkbox selecting the database columns image of table show data

回答

0
<?php 
    $columns = $_POST['check_list']; // array 
    foreach($columns as $column) 
    { 
     $cols .= $column . ','; 
    } 
    $sql = "SELECT " . $cols . " FROM teachers"; 
    // do you stuff 
+0

使用你的方法,错误说“数组到字符串转换”。如何在表格中显示阵列数据​​ –

0

你的列名不逗号通过阵列分隔所以只是环和追加一个逗号每个元素的再循环结束后仅删除最后一个逗号

<?php 
    $check_list= $_POST['check_list']; // array 
    foreach($colnames as $check_list) 
    { 
     $cols .= $colnames . ','; 
    } 
    $cols = substr($cols,0,strlen($cols)-1); 
    $sql = "SELECT " . $cols . " FROM teachers"; 
    //rest of the code 

?> 
+0

没关系。但是如何在html表格中显示数据呢? @Atal Kishore –

+0

好的。我似乎没有得到任何回应。有人可以帮我吗? –

相关问题