0

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?

4

2 回答 2

2

在您的 HTML 中添加一个隐藏的输入,该输入将收集所有 ID:

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

然后,当您提交表单时,您可以遍历所有这些 ID 并更新您的数据库:

foreach( $_POST['ids'] as $id )
{
    $price = $_POST[$id];
     $query = "
        UPDATE retail_pricing
        SET pricing = {$price}
                    WHERE id = {$id} ";
    mysqli_query($connection, $query);
}
于 2013-09-25T16:09:19.840 回答
2
foreach($_POST as $key => $value) {
    if(is_numeric($key))
    {
        $query = "UPDATE retail_pricing SET pricing = $value  WHERE id = $key ";
        mysqli_query($connection, $query);
    }  
}
于 2013-09-25T16:07:08.427 回答