I have two tables (groups and parties) in a many to many relationship using a lookup table called groupparty. I’d like to be able to assign prices to each party, such that a party that belongs to two groups might have one price in one group and a different price in another group. In the table groupparty, I have three columns: groupid, partyid and totalprice. So, to assign prices, I have the following form:
<form action="" method="post">
<?php foreach ($groups as $group): ?>
<input type="hidden" name="groupids[]"
value="<?php echo $group['id']; ?>"/>
<?php htmlout($group['groupname']); ?>
<label for="totalprice">Price:
<input type="text" name="totalprices[]" id="totalprice"
value="<?php htmlout($totalprice); ?>"/></label><br />
<?php endforeach; ?>
<input type="hidden" name="id" value="<?php htmlout($id); ?>"/>
<input type="submit" name="action" value="Set"/>
</form>
On the mysql side, I’ve come as far as the following script. It almost works, except that it inserts the last totalprice value entered in the form above into all the associated groups. Any other totalprice values are lost – I’m left with only one value assigned:
if (isset($_POST['action']) and $_POST['action'] == 'Set')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
foreach($_POST['groupids'] as $groupid)
foreach($_POST['totalprices'] as $totalprice)
{
$sql = "UPDATE groupparty SET
totalprice = '$totalprice'
WHERE groupid = '$groupid'
AND partyid = '$id'";
mysqli_query($link, $sql);
}
}
Any suggestions would be welcome. Thanks.
You can adjust your structure to make the updating a lot easier – just pass the group id as an key to the
totalprices[]array in your HTML:Then, you can just loop through that one array:
The problem with your current structure is that for every group id, you loop through all of the prices, so obviously when the last iteration is reached, the last value is overwriting the previous.
Given that you have groups 1, 2 and 3 and prices 20, 25 and 30. Your loop currently loops through the values like this:
When you actually wanted this:
As you can see from the upper table, all groups get the price
30as that is the last price each of those get.