I am trying to select columns from a mysql table based on checkboxes (columns provided as check boxes). The following is a reproducible example.
<?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>
Understandably when I select one checkbox the table gets returned. When I select both the checkboxes, I am getting the error message echoed from this: die("Query to show fields from table failed");
.
I think I have to get the last trailing comma from the $value. How do I do it?
Aucun commentaire:
Enregistrer un commentaire