gpt4 book ai didi

php - 如何从另一个表更新mysql pdo中的字段

转载 作者:可可西里 更新时间:2023-11-01 08:24:39 26 4
gpt4 key购买 nike

<分区>

这不是一个重复的问题。前一个问题与PDO无关。我在 mysql 中有两个表:

USERS
-------------------------------------
employeeid | name | saving | salary
-------------------------------------
12 | Bob | 100 | 1000
23 | Joe | 50 | 800

USERS table
employeeid
name
saving
salary

和:

EMPLOYEE
-----------------------------------
id | managerid | workerid
-----------------------------------
1 | 12 | 23

EMPLOYEE table
id
managerid FOREIGN KEY
workerid FOREIGN KEY

1-(manager 和 worker 都是 employee)为了更新 workerid 的保存字段(比如 +$10),字段 salary 需要更新 -$10

2- 输入变量来自 PHP 表单作为 name ,所以逻辑流程是:

name  > find employeeid (id) from USERS > find managerid (id2) from EMPLOYEE > find employeeid (id3) from USERS > update saving and salary

所以单独的sql语句可以写成:

id = SELECT employeeid FROM USERS WHERE name = $name;   //find id of employee in USERS
id2 = SELECT managerid FROM EMPLOYEE WHERE workerid = id; //find id of worker in EMPLOYEE
UPDATE USERS SET saving = saving + 10, salary = salary -10 WHERE employeeid = id2;

是否可以将这 3 个语句合而为一(PDO 格式)。上面的msql PDO格式(用PHP):

$sql = "SELECT employeeid FROM USERS WHERE name=:namepara";
$sttm = prepare($sql);
$sttm->execute(array(":namepara"=>$name));
$row=$sttm->fetch(PDO::FETCH_ASSOC);

$sql2 = "SELECT managerid FROM EMPOYEE WHERE workerid=:idpara";
$sttm2 = prepare($sql2);
$sttm2->execute(array(":idpara"=>$row['employeeid']));
$row2=$sttm2->fetch(PDO::FETCH_ASSOC);

$sql3 = "UPDATE USERS SET saving = saving + 10, salary = salary - 10 WHERE
employeeid=:id2para";
$sttm3 = prepare($sql3);
$sttm3->execute(array(":id2para"=>$row2['managerid']));
$row3=$sttm3->fetch(PDO::FETCH_ASSOC);

如有任何帮助,我们将不胜感激!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com