[英]Change MySQL prices with just 1 input field based on a custom formula for each id?
I have a database with some prices in it: 我有一个包含价格的数据库:
But I want that I can give every id a formula like : [thatnumber]
* or / or - or + . 但是我希望我可以给每个id一个像这样的公式:
[thatnumber]
*或/或-或+。 = [AndShowThatPrice]
=
[AndShowThatPrice]
So for a example: I want just to type here a price: 举个例子:我只想在这里输入一个价格:
If I type 10 then I want that the formula for the id=0
will be like: 10 * 8 = 80 <<--- Update to that price in MySQL 如果我输入10,那么我希望
id=0
的公式如下:10 * 8 = 80 << ---在MySQL中更新为该价格
And so I want to give each id a formula So for id=1
example: 10 + 140 = 150 <<--- Update to that price in MySQL 所以我想给每个id一个公式所以
id=1
例子:10 + 140 = 150 << ---在MySQL中更新到该价格
* I just want to type the total price in one field, like : 10, then from that value the math will be made and the total price will updated in the database * *我只想在一个字段中输入总价格,例如:10,然后根据该值进行数学运算,总价格将在数据库中更新*
You would need at least one other field on the table that would contain your math for prices. 您将在表上至少需要一个其他字段,其中包含您的价格数学。 For instance a field called math that would be +140.
例如,名为math的字段将为+140。 The you could do an update statement with one input box
您可以使用一个输入框来执行更新语句
You can use a CASE
statement in your update clause based on the id. 您可以在id的更新子句中使用
CASE
语句。 It looks something like this: 看起来像这样:
UPDATE myTable
SET price =
CASE WHEN id = 0 THEN (10 * 8)
WHEN id = 1 THEN (10 + 140) ELSE
0 END;
You will have to determine a business rule to fall back on if the id isn't in any of your categories. 如果ID不在您的任何类别中,则必须确定要依赖的业务规则。 In my example, I just set it to 0.
在我的示例中,我只是将其设置为0。
One possible solution could be: You have four possible operations and you can say that each operation 一种可能的解决方案可能是:您有四个可能的操作,并且您可以说每个操作
have one id number, eg: 0 for +, 1 for -, 2 for * and 3 for / then use the module operator to determine which operator use, something like: 有一个id号,例如:0表示+,1表示-,2表示*,3表示/,然后使用模块运算符确定使用哪个运算符,例如:
For example if you're using PDO. 例如,如果您使用的是PDO。
... get the PDO conn ...获取PDO conn
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable');
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
$operator = $row['id'] % 4;
switch ($operator) {
case 0:
$newValue = $inputField + price;
break;
case 1:
$newValue = $inputField - price;
break;
case 2:
$newValue = $inputField * price;
break;
default:
$newValue = $inputField / price;
}
$updateStmt = $conn->prepare('UPDATE myTable set prijs = :pirjs WHERE id = :id');
$updateStmt->execute(array('prijs' = $newValue, 'id' => $row['id']));$stmt->execute(array('id' => $id));
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.