[英]select mysql columns with checkbox and display data in html table,php
我有5個月的php和mysql工作經驗。 我的問題是如何選擇復選框來選擇mysql數據庫表中的某些列,並在php的html表中顯示這些選定列的數據? 請在下面查看我的代碼,並幫助我解決該問題。
復選框代碼:
<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>
以下是圖像: 選擇數據庫列的復選框的 圖像表顯示數據的圖像
<?php
$columns = $_POST['check_list']; // array
foreach($columns as $column)
{
$cols .= $column . ',';
}
$sql = "SELECT " . $cols . " FROM teachers";
// do you stuff
您的列名不用逗號分隔,因此只需遍歷數組並為每個元素附加一個逗號,然后在循環結束后刪除最后一個逗號即可
<?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
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.