Reputation: 143
I am working on an invoice in which i want to update table data.
My script only updates the last row of the table. Can this work with this foreach loop?
Following is the script I am trying to do it with:
HTML input fields
<tr>
<input type="hidden" name="data['+i+'][Id]" value="<?php echo $Id; ?>" >
<input type="hidden" name="data['+i+'][ItemId]" value="<?php echo $item_Id; ?>" >
<td><input type="text" value="<?php echo $item; ?>"></td>
<td><input type="text" name="data['+i+'][QTY]" value="<?php echo $Quantity; ?>"</td>
<td><input type="number" value="<?php echo $price; ?>"></td>
<td><input type="number" name="data['+i+'][total]" value="<?php echo $total; ?>"></td>
</tr>
PHP
if (isset($_POST['submit'])) {
foreach($_POST['data'] as $key => $data) {
$Id = intval($data['Id']);
$itemId = intval($data['ItemId']);
$QTY = intval($data['QTY']);
$Total = intval($data['total']);
if($itemId > 0) {
$query = $db - > prepare("UPDATE table SET QTY = :QTY where id = :ID ");
$query - > execute(array(':ID' => $ID, ':QTY' => $QTY));
}
}
}
Upvotes: 1
Views: 155
Reputation: 42879
This does not seem to be valid syntax:
data['+i+']
PHP will consider this as a string with a fixed value, meaning your $_POST[data]
array will only have one key, each new occurrence overwriting the previous one. In the end it will look like this:
$_POST[data] == array( '+i+' => array(
'Id' => ...,
'ItemId' => ...,
'QTY' => ...,
'total' => ...
));
You probably want to use some PHP in your code in order to properly write the i
index:
<tr>
<input type="hidden" name="data[<?php echo $i; ?>][Id]" value="<?php echo $Id; ?>" >
<input type="hidden" name="data[<?php echo $i; ?>][ItemId]" value="<?php echo $item_Id; ?>" >
<td><input type="text" value="<?php echo $item; ?>"></td>
<td><input type="text" name="data[<?php echo $i; ?>][QTY]" value="<?php echo $Quantity; ?>"</td>
<td><input type="number" value="<?php echo $price; ?>"></td>
<td><input type="number" name="data[<?php echo $i; ?>][total]" value="<?php echo $total; ?>"></td>
</tr>
and increment it for each row.
Upvotes: 3