KickingLettuce KickingLettuce - 10 months ago 134
MySQL Question

Updating Multiple HTML Fields into MySQL Database with PHP

This seems like a very basic task; I am not sure if I am having a brain cramp or if I ran into something a bit more rare. But it doesn't seem so.

I have a table called

products
that have these columns:
ID, Model, Cost, Quantity


My HTML form prints out all price and quantity discounts by model; I loop thru like this:

<form method="post">

<table>
<tr>
<th>Quantity</th>
<th>Pricing</th>
</tr>

<?php while ($row = mysqli_fetch_array($result)) { ?>

<tr>
<td><?php echo $row['model']; ?></td>
<td><input type="text" name="<?php echo $row['id']; ?>" value="<?php echo $row['cost']; ?>" /></td>

</tr>

<?php } ?>

</table>


<input type="submit" name="retail_price" value="Update Pricing" />

</form>


So it prints out all pricing in text fields, and has a button so that there can be "mass" update to pricing.

My question is regarding the
PHP
where I am stuck:

if (isset($_POST['retail_price'])) { // THIS CODE IS NOT COMPLETE!

$query = "
UPDATE retail_pricing
SET pricing = {$new price}
WHERE id = {$id} ";
mysqli_query($connection, $query);

}


The issue I have run into, I want to go through each field and update each one. Doing a quick search for other Stack questions, it seems like I need to use a
foreach
to iterate through each field. Is this correct? Also, would the query be in the loop as well?

Answer Source
foreach($_POST as $key => $value) {
    if(is_numeric($key))
    {
        $query = "UPDATE retail_pricing SET pricing = $value  WHERE id = $key ";
        mysqli_query($connection, $query);
    }  
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download