[英]How to update table based from two different tables in php MySQL?
I have 3 tables reservation, orders, and inventory. 我有3张桌子的预订,订单和库存。 In reservation i have orders for example (2 apples and an orange).(reservation.confirmation=orders.confirmation). 在预订中,我有订单(例如2个苹果和一个橘子)。(reservation.confirmation = orders.confirmation)。 I would like to update apple and orange inventory.sold when reservation.status changed to "Delivered" 当保留.status更改为“已交付”时,我想更新苹果和橙库存.sold
reservation
---------------------------
confirmation | status
EX-10 pending
orders
---------------------------
confirmation | product | qty
EX-10 apple 2
EX-10 orange 1
inventory
---------------------------
id | nameofproduct | sold
1 apple -->update to 2
2 orange -->update to 1
HERE is my code so far. 到目前为止,这里是我的代码。
$confirmation = $_POST['confirmation'];
$status=$_POST['status'];
mysql_query("UPDATE reservation SET status='$status' WHERE reservation_id='$roomid'");
if ($status=='Delivered')
{
mysql_query("UPDATE inventory SET sold = (SELECT qty FROM orders where confirmation='$confirmation') where nameofproduct=(SELECT prduct FROM orders where confirmation='$confirmatioin')");
}
Please help for the right query. 请帮助进行正确的查询。 Thanks 谢谢
Have you heard about TRIGGERS
? 您听说过TRIGGERS
吗? See: http://www.sitepoint.com/how-to-create-mysql-triggers/ 请参阅: http : //www.sitepoint.com/how-to-create-mysql-triggers/
I've made you what you want, I didn't check it so probably has errors, let me know if you have problems with it. 我已经为您提供了想要的东西,但我没有对其进行检查,因此可能有错误,如果您有任何问题,请告诉我。
DELIMITER $$
CREATE TRIGGER inventory
AFTER UPDATE ON reservation FOR EACH ROW
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE product VARCHAR(200); -- SHOULD BE THE SAME TYPE AND LENGTH AS order.product
DECLARE qty INT; -- SHOULD BE THE SAME TYPE AND LENGTH AS order.qty
DECLARE orders_cursor CURSOR FOR SELECT o.product, o.qty FROM orders o WHERE o.confirmation = NEW.confirmation;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
IF (NEW.status = 'delivered') THEN
open orders_cursor;
get_orders: LOOP
FETCH orders_cursor INTO product, qty;
IF finished = 1 THEN
LEAVE get_orders;
END IF;
-- UPDATE INVENTORY
UPDATE inventory i SET i.sold = qty WHERE i.nameofproduct = product;
END LOOP get_orders;
close orders_cursor;
END IF;
END
$$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.