简体   繁体   中英

PHP get the table data row input value using loop

I am having a issue in getting the correct value from the table .

The issue I encountered:

  • When I choose the second checkbox the and input a quantity , it is Undefined offset: 0

But the value of the checkbox is working and correct.

What I am expecting is when I choose the second or other checkbox (exclude first checkbox ), I should get the value of that input field.

HTML

<?php foreach($results as $row) { ?>
<tr>
    <td><input type="checkbox" name="products[]" value="<?php echo $row->items_id; ?>"></td>
    <td><?php echo $row->item_name; ?></td>
    <td><input type="number" name="quantity[]" class="form-control"></td>
</tr>
<?php } ?>
<input type="submit" name="process" class="btn btn-primary" value="Process">

PHP

$quantity = $_POST['quantity'];
$products = $_POST['products'];
$count_selected = count($products);

for($i=0; $i< $count_selected; $i++){
    var_dump($quantity[$i]); exit;
}

视图的样本图像

The problem with checkboxes is that an unchecked one submits no value so your $_POST['products'] and $_POST['quantity'] arrays may have different lengths.

I'd combine using a hidden input with specific array indexes.

For example

<?php foreach($results as $row) : ?>
<tr>
    <td>
        <input type="hidden" name="products[<?= $row->items_id ?>]" value="0">
        <input type="checkbox" name="products[<?= $row->items_id ?>]" value="1">
    </td>
    <td><?= htmlspecialchars($row->item_name) ?></td>
    <td><input type="number" name="quantity[<?= $row->items_id ?>]" class="form-control"></td>
</tr>
<?php endforeach ?>

Then the arrays will have the same indexes and you can iterate them with a foreach

foreach ($_POST['products'] as $itemId => $checked) {
    // $checked represents the state of the checkbox
    // you can access quantity via $_POST['quantity'][$itemId]
}

You could even create a nice filtered array of quantities via

$selections = $_POST['products'];
$quantities = array_filter($_POST['quantity', function($itemId) use ($selections) {
    return $selections[$itemId];
}, ARRAY_FILTER_USE_KEY);

first, define array variable. $products =array( ); $quantity=array( ); other wise every thing seems fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM