有多少苹果?立即在PHP中更新这些唯一的数据库条目
我有一个数据库:“example_DB”,其中有一个客户信息表:“custinfo_tb”和客户属性表:“custatt_tb” custinfo_tb有以下共谋:有多少苹果?立即在PHP中更新这些唯一的数据库条目,php,mysql,mysqli,Php,Mysql,Mysqli,我有一个数据库:“example_DB”,其中有一个客户信息表:“custinfo_tb”和客户属性表:“custatt_tb” custinfo_tb有以下共谋: cust_id name apples cust_id age allowance favcolor 其中苹果是每个客户拥有的苹果数量 custatt_tb有以下共谋: cust_id name apples cust_id age allowance favcolor 现在,我正在尝试用PHP开发代码,
cust_id
name
apples
cust_id
age
allowance
favcolor
其中苹果是每个客户拥有的苹果数量
custatt_tb有以下共谋:
cust_id
name
apples
cust_id
age
allowance
favcolor
现在,我正在尝试用PHP开发代码,确定客户收到的苹果数量。这取决于他们的年龄和津贴。但只有特定颜色的顾客才能得到苹果
例如:Jon已经有3个苹果,客户ID为1。他的零用钱是25美元,他最喜欢的颜色是蓝色
Jasmine已经有12个苹果了,客户ID为2。她的零用钱是10美元,他最喜欢的颜色是红色
康纳已经有2个苹果了,客户ID为3。他的零用钱是22美元,他最喜欢的颜色是绿色
Richard已经有8个苹果,客户ID为4。他的零用钱是30美元,他最喜欢的颜色是红色
每个人都是12岁
我需要什么代码来更新这两个表:
任何喜欢红色的顾客都会得到更多的苹果。他们得到的苹果数量是
苹果数量=年龄*津贴
在上面的例子中,Jasmine将以132个苹果结束,Richard将以368个苹果结束 这是一个奇怪的问题,我知道,但出于隐私的原因,我用实际的代码代替苹果之类的!问题是一样的。
谢谢你的帮助!我有一种感觉,我需要在其他FOREACH语句中包含FOREACH语句,但我无法让它工作。谢谢 编辑:这就是我到目前为止所拥有的
$con=mysqli_connect("private","private","private","example_DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$color = $_POST["colorpicked"];
$age = $_POST["age"];
$getallowance = mysqli_query($con, "SELECT allowance FROM custatt_tb WHERE favcolor = '$color'");
$allowance= mysqli_fetch_array($getallowance);
foreach ($allowance as &$value) {
$applesgiven= ($value * $age);
$getnames = mysqli_query($con, "SELECT cust_id FROM custatt_tb WHERE favcolor= '$color' AND allowance = '$value'");
$getnames2 = mysqli_fetch_array($getnames);
foreach ($getnames2 as &$value2 ) {
$getapples = mysqli_query($con, "SELECT apples FROM custinfo_tb WHERE cust_id = '$value2'");
$getapples2 = mysqli_fetch_array($getapples);
$applesold = $getapples2['apples'];
$applesnew = ($applesold + $applesgiven);
if (!mysqli_query($con, "UPDATE custinfo_tb SET apples = '$applesnew' WHERE cust_id = '$value2'")) {
// die('Error: ' . mysqli_error($con));
// }
}
}
不需要多次访问数据库,您可以在一个纯SQL查询中完成所有操作
UPDATE custinfo\u tb c加入custatt\u tb a
在c.cust\u id=a.cust\u id上
设置苹果=苹果+津贴*年龄
其中a.favcolor=‘红色’;
结果:
| CUST_ID | NAME | APPLES |
|---------|---------|--------|
| 1 | Jon | 3 |
| 2 | Jasmine | 132 |
| 3 | Connor | 2 |
| 4 | Richard | 368 |
|客户ID |姓名|苹果|
|---------|---------|--------|
|1 |乔恩| 3|
|2 |茉莉花| 132|
|3 |康纳| 2|
|4 |理查德| 368|
这里是演示始终显示您迄今为止尝试过的代码,以便我们能够更好地了解anwerWow,我不知道SQL可以做到这一切。我得把所有的东西都查一下,但看起来不错。谢谢