簡體   English   中英

如何使用 php 和 sql 更新單列的動態行數?

[英]How to update a single column of a dynamic number of rows using php and sql?

編輯 - 免責聲明:PHP 和 SQL 的菜鳥

我需要根據所選蔬菜從每個金額行中減去不同的值。

例如:如果用戶選擇西紅柿和辣椒,我需要分別從這些數量中減去 200 和 400。

有沒有辦法將這些值附加到蔬菜上? 我有一個看起來像這樣的數組:

**數組([0] => 西紅柿 [1] => 洋蔥 [2] => 菠菜 **

配料表+----+-------------+---------+--------+-------+ | id | name | type | amount | unit | +----+-------------+---------+--------+-------+ | 1 | tomatoes | veggies | 1000 | grams | | 2 | onions | veggies | 1000 | grams | | 3 | spinach | veggies | 1000 | grams | | 4 | capsicum | veggies | 1000 | grams | | 5 | basil | veggies | 1000 | grams | +----+-------------+---------+--------+-------+ +----+-------------+---------+--------+-------+ | id | name | type | amount | unit | +----+-------------+---------+--------+-------+ | 1 | tomatoes | veggies | 1000 | grams | | 2 | onions | veggies | 1000 | grams | | 3 | spinach | veggies | 1000 | grams | | 4 | capsicum | veggies | 1000 | grams | | 5 | basil | veggies | 1000 | grams | +----+-------------+---------+--------+-------+

我在 PHP 中有一系列蔬菜。 我正在考慮迭代該數組並根據該蔬菜更新該列。 所以可能:

foreach($vegetable as $subject) 
     ($query = $conn->prepare("UPDATE ingredients set amount = amount - ? where `name` = '$item';"))
     $query->bind_param("i", $amount);
     $query->execute();
     $insertresult = $query->get_result();
`

問題是,我不知道如何更改 $amount 並且我知道這段代碼根本不會減去值。

目前,我已將 $amount 硬編碼為 200,但我不想只將每行的金額更新為 200。我需要它以某種方式從當前值中減去 200 - 在本例中為 1000 ,所以 1000 - 200,並將值更新為 800。對於辣椒,我需要減去 400。

我查看了在 MySQL 的 1 列中更新多行,但這似乎不是動態的。 它假設我們事先知道要更改哪些行以及最終值是什么。

編輯:我剛剛檢查了Mysql 查詢:將值減 1 ,我認為這解決了減去值的問題,但它沒有解釋如何將這些值鏈接到 PHP 中的蔬菜。 示例:如何將 200 的數量與西紅柿和 400 與辣椒的數量聯系起來?

編輯 2:更新代碼以減去值和更正語法,澄清問題。

答案是修改我獲取數據的方式。 所以從這里:

<input type="checkbox" name="topping[]" id="toppingCheckbox" value="tomatoes">

我需要更改名稱和值屬性:

<input type="checkbox" name="topping[tomatoes]" id="toppingCheckbox" value="200">

減法是一個簡單的 sql 查詢,在這里回答。 Mysql查詢:減1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM