简体   繁体   English

使用PHP将多个HTML字段更新到MySQL数据库

[英]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 我有一个名为products的表,其中包含以下列: ID, Model, Cost, Quantity

My HTML form prints out all price and quantity discounts by model; 我的HTML表格按模型打印出所有价格和数量折扣; 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: 我的问题是关于PHP卡在哪里的:

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. 快速搜索其他Stack问题,似乎我需要使用一个foreach来遍历每个字段。 Is this correct? 这个对吗? Also, would the query be in the loop as well? 另外,查询是否也会在循环中?

foreach($_POST as $key => $value) {
    if(is_numeric($key))
    {
        $query = "UPDATE retail_pricing SET pricing = $value  WHERE id = $key ";
        mysqli_query($connection, $query);
    }  
}

Add a hidden input in your HTML that will collect all IDs: 在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>

then when you submit the form you can loop through all those IDs and update you DB: 然后,当您提交表单时,您可以遍历所有这些ID并更新您的数据库:

foreach( $_POST['ids'] as $id )
{
    $price = $_POST[$id];
     $query = "
        UPDATE retail_pricing
        SET pricing = {$price}
                    WHERE id = {$id} ";
    mysqli_query($connection, $query);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM