首页 > 解决方案 > How to get PHP to match textbox with corresponding checkbox from a form

问题描述

Basically, I have about 700 customers in a database and I show them in a page with a loop, which goes through of all 700 customers. This loop adds a checkbox next to each customer, so you can select which one of them you want to go onto the next days schedule, on average this will be about 30 customers.

This is my form:

<table>
<tr>
    <td class="search_result_fullname"><?php echo $row['fullname']; ?></td>
    <td class="search_result_price">&pound;<input type="text" name="price[]" value="<?php echo $price; ?>" class="schedule_price"></td>
    <td class="search_result_phone"><a href="tel:<?php echo $phone; ?>"><?php echo $phone; ?></a></td>
    <td class="search_result_checkbox"><input type="checkbox" name="customerid[]" value="<?php echo $row['id']; ?>"></td>
</tr>
<tr>
    <td colspan="5"><input type="text" name="remarks[]" placeholder="Remarks" class="remarks"></td>
</tr>
</table>

Once this form is submitted, then it reloads the page and I have a if(isset($_POST['add'])){ in place. I've tried various different loops and I cant for the life of me work out how to do it.

So, the form is submitting an array of only checkboxs that are checked. If I call print_r($_POST['customerid']); to verify it shows that this is working as expected. Then, if i select customer 50 and 51, then it should return an array with just those two.

Now the problem is that I also want to get the correct price value for each customer (50 and 51), but the array for $_POST['price'] is submitting the price for all 700 customers. How do I get the price to correspond to the correct customers that I've checked?

Any support is greatly appreciated.

标签: php

解决方案


您可以将price数组设置为按客户 ID 进行索引:

<input type="text" name="price[<?=$row['id']?>]" value="<?=$price?>" class="schedule_price">

...然后按客户 ID 参考价格:

$customerIds = $_POST['customerid'];
$prices = $_POST['price'];

foreach ($customerIds as $customerId) {
  $price = $prices[$customerId];
}

推荐阅读