Md.Shapan Hossain Md.Shapan Hossain - 22 days ago 6
PHP Question

The checkbox's do not hold all value when I select more then one checked

I'm new in php programming ..and I want insert employee attendance. when I checked more then one checkbox it take two checkbox value 1 and other checkbox value 0 ...so how can i solve this please help me.. this is my form code

<form action="coll.php" method="post" name="create_grading" id="create_grading">
<table width="30%" border="0" cellpadding="2" cellspacing="3" class="mainTable">
<tr>
<th><input type="checkbox" id="selectall" /></th>
<th>name</th>
</tr>
<?php
$sql = "select * from employee";
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><input type="hidden" name="eid[]" value="<?php echo $row['eid']; ?>"/>
<input name="status[]" class="case" type="checkbox" value="1" /><input name="status[]" class="case" type="hidden" value="0" /></td>
<td align="center"><?php echo $row['employee_name'] ?></td>
</tr>
<?php }; ?>

<tr>
<td></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>


this is my insert code

$host = "localhost";
$user = "root";
$pass = "";
$db = "multiple_row_insert";
$con = mysqli_connect($host, $user, $pass, $db);


if (isset($_POST['Submit'])) {
$eid = $_POST['eid'];
$count = count($eid);
for ($i = 0; $i < $count; $i++) {
$status = $_POST['status'][$i];
$eid2 = $_POST['eid'][$i];
$query = "INSERT INTO time(eid,status) VALUES ('$eid2','$status')";
$query = mysqli_query($con, $query);
}
}

Answer

You want your value="0" to come before the value="1", so that when checked, the second will overwrite the first. Also, you want to match the indexes. The way you have it now is dynamic [] and it increments each one. Something like:

$i = 0;
while ($row = mysqli_fetch_array($query)) {
    $i++;
    ?>   
    <tr>
        <td><input type="hidden" name="eid[<?php echo $i; ?>]" value="<?php echo $row['eid']; ?>"/>               
            <input name="status[<?php echo $i; ?>]" class="case" type="hidden" value="0" />
            <input name="status[<?php echo $i; ?>]" class="case" type="checkbox" value="1" /></td>
        <td align="center"><?php echo $row['employee_name'] ?></td>
    </tr>
<?php }; ?>

It may look better to echo the HTML and/or use Heredoc. Also, consider: <?= $i ?>