Okay, so I have a PHP array pulling from a mysql table. The array is generated based on the items in a table where items are frequently added and deleted. I have a button next to the item name, "Submit." I want the button to identify with the item that is in the same index. It will then pass the item submitted item to a new table.
<form class="omb_loginForm" action="inc/contribute_item.php" autocomplete="off" method="POST">
<?php
$item_array;
$index = 0;
$index_2 = 1;
$r = "r";
$b="b";
foreach ($item_array as $id_array){ ?>
<tr id="<?php echo $r.$index_2; ?>">
<td><?php echo $item_array[$index] ?></td>
<td> <?php echo $quantity_array[$index]; ?></td>
<td> <?php echo $price_array[$index];
$selectedItem = $item_array[$index]; ?>
<input type='hidden' name='hidden' value='<?php $selectedItem ?>'>
<input type='submit' name='submit' value"submit">
</form> </td>
<?php $index++;
$index_2++; ?>
</tr>
Here is the PHP:
if ($_POST['submit']) {
$connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$user_contrib = $_SESSION['first_name'];
$selected = $selectedItem;
$connect->query("UPDATE `items` SET `purchased_by` = '$user_contrib' WHERE `name` = '$selected'");
}
You're on the right track, just make sure that your opening and closing html tags are properly aligned.
If you want to transmit the selected value via an hidden input, make sure, that each of these inputs is inside its own form together with the corresponding submit button:
<!-- row 1: -->
<form action="inc/contribute_item.php" method="post">
<input type="hidden" name="myValue" value="1"/>
<input type="submit" value="submit"/>
</form>
<!-- row 2: -->
<form action="inc/contribute_item.php">
<input type="hidden" name="myValue" value="2"/>
<input type="submit" value="submit"/>
</form>
Then in PHP access the selected value by using $_POST['myValue']
.
Don't nest form tags. And don't put form tags between your table, tr, td tags. Close them in the same order you open them.
To be more specific, this is how your loop could look like:
<!-- don't start your form here -->
<table>
<?php foreach(...) { ?>
<tr>
<td>...</td>
<td>
<form action="inc/contribute_item.php" method="post">
<input type="hidden" name="myValue" value="<?= $index ?>"/>
<input type="submit" value="submit"/>
</form>
</td>
</tr>
<?php } ?>
</table>
Yet another option would be to use <input type="radio" ... />
elements in each row. This way you could use just one global form:
<form action="inc/contribute_item.php" method="post">
<table>
<?php foreach(...) { ?>
<tr>
<td>...</td>
<td>
<input type="radio" name="myValue" value="<?= $index ?>"/>
</td>
</tr>
<?php } ?>
</table>
<input type="submit" value="submit"/>
</form>