5

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.

3 Answers 3

9

Do it like this:

if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $check) {
        echo $check; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.

You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.

You are also overwriting your InspectRoomNo every row, so you should use an array there as well.

The form side would look something like:

<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox"  ></td>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.