The following is my form where I have two different $_POST arrays, "ids" and "quantities". I'm trying to loop through them so I can update a database column.
My form:
<form action="" method="post">
<ul>
<?php foreach($rows as $row) { ?>
<li>
<input type="hidden" name="ids[]" value="<?php echo $row['id']; ?>">
</li>
<li>
<input type="text" name="quantities[]" value="1" size="3">
<?php echo $row['title']; ?>
</li>
<?php } ?>
<li>
<br><input type="submit" value="Submit New Release Edits" name="submit">
</li>
</ul>
</form>
The code I am attempting to run in order to update the database properly is:
if(isset($_POST['submit'])) {
foreach($_POST['quantities'] as $quantity) {
foreach($_POST['ids'] as $id) {
$stmt = $db->prepare("UPDATE titles SET release_quant=:release_quant WHERE id=:id");
$stmt->bindValue(':release_quant', $quantity, PDO::PARAM_INT);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
}
}
}
I know the code isn't correct, because it doesn't loop through the quantity and id arrays at the same time. How do I need to adjust my code?
Try this: (replaced the second loop by direct access, so you only get the ID wanted)
$i = 0;
if(isset($_POST['submit'])) {
foreach($_POST['quantities'] as $quantity) {
$id = $_POST['ids'][$i];
$stmt = $db->prepare("UPDATE titles SET release_quant=:release_quant WHERE id=:id");
$stmt->bindValue(':release_quant', $quantity, PDO::PARAM_INT);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$i++;
}
}