Krish
Krish

Reputation: 39

checkbox array with corresponding input value

I fetch data from mysql in php. List all items with checkbox and quantity (rqty) as input value where user can enter quantity. But I'm not able to relate checkbox with corresponding input value (rqty) in an array. If I select first checkbox and enter quantity it works fine but if select any other checkbox and enter quantity, it's not getting updated in database. My code is as below:

<?php
If (isset($_REQUEST['submit1'])!='') {
foreach($_POST['itm'] as $key=>$itm) {
$odate=date("Y-m-d H:i:s");
$rqty=$_POST['rqty'][$key];
$itm=$_POST['itm'][$key]; 
$sql1="insert into table (itemtype,itemname,qty ,retdate,reason) select itemtype, itemname, '$rqty', '$odate', 'Return' from stock where itemname='$itm';
mysql_query($sql1);
}
}
?>
<p>
<form action="" method="post" name="form1">
<?php
$query3 = "SELECT id, category, itemtype, itemname, qty, status FROM stock where location='godown'";
$comments3 = mysql_query($query3);
$qty = mysql_num_rows($comments3);
echo "Consumable Items: " . $qty;
print "<table class='blue'>
  <thead>
<tr>
<td width=100>Return</td>
<td width=100>Category</td>
<td width=100>Item Type</td>
<td width=100>Item Name</td>
<td width=100>Available Qty.</td>
<td width=100>Return Qty.</td>
<td width=100>Status</td>
</tr>
</thead>";

while($row1 = mysql_fetch_assoc($comments3))
{
$it=$row1['itemname'];
print "<tbody>";
print "<tr>";
print "<td><input type='checkbox' name='itm[]' value='$it'></td>";
print "<td>" . $row1['category'] . "</td>";
print "<td>" . $row1['itemtype'] . "</td>";
print "<td>" . $row1['itemname'] . "</td>";
print "<td>" . $row1['qty'] . "</td>";
print "<td><input type='text' name='rqty[]' placeholder='Enter Qty' /></td>";
print "<td>" . $row1['status'] . "</td>";
print "</tr>";
print "</tbody>";
}
print "</table>";
?>
<input type='submit' name='submit1' value='Return' />

In inspect I can see that all rqty[] are getting posted with blank data. But in case of itm, only itm which is selected is getting posted which is correct.

enter image description here

Upvotes: 1

Views: 91

Answers (2)

Krish
Krish

Reputation: 39

Since I did not receive any solution for this, I changed the approach. Now handling each checkbox separately and not using any array. Added submit button in form list and posting required values to other php page where it's processed further.

Upvotes: 1

Lexxusss
Lexxusss

Reputation: 552

That's because of your loop:

foreach($_POST['itm'] as $key=>$itm) {...

and input "itm" is checkbox: <input type='checkbox' name='itm[]' value='$it'></td>

For instance, if you have 5 checkboxes in the form-table but only 2 of them was checked - then you'll have only 2 items in array $_POST['itm'], not 5.

To fix this issue you need to loop through $_POST['rqty'] instead of $_POST['itm']

Upvotes: 0

Related Questions