Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through an array of checkbox

Tags:

php

I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.

When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.

My code so far FORM:

<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox"  ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>

The insert: fetchs $Items from table

while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}


foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);

if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}

The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.

Can anyone help me sort this issue.

Many thanks.

like image 557
DCJones Avatar asked Dec 27 '22 09:12

DCJones


2 Answers

Do it like this:

if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $check) {
        echo $check; 
    }
}
like image 132
Amir Bilal Avatar answered Dec 28 '22 23:12

Amir Bilal


You should put the item id inside the checkbox name:

<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>

Then, you can simply iterate over it:

foreach ($_POST['check'] as $id => $value) {
    // do stuff with your database
}

I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.

like image 35
Ja͢ck Avatar answered Dec 28 '22 22:12

Ja͢ck