I have a script in PHP that I need to turn into a MySQL procedure. I can't run the PHP script because this must be executed by a MySQL trigger. Because I have no idea how to fix this in all MySQL, I wrote it in PHP.
The PHP script below needs to be changed to a MySQL procedure. The 25
and http://www.someurl.com/
are variables that filled from the trigger (new.order_id
/ new.store_url
):
$query = "SELECT
oc_order_product.quantity,
oc_order_option.option_value_id,
product.id
FROM oc_order_product
JOIN oc_order_option
ON oc_order_option.order_id = oc_order_product.order_id
JOIN product
ON product.oc_product_id = oc_order_product.model
WHERE oc_order_product.order_id = '25' AND oc_order_product.store_url = 'http://www.someurl.com/'";
$result = $mysqli->query($query);
while($row = $result->fetch_object()){
$query = "UPDATE product_option_value SET quantity = quantity - {$row->quantity} WHERE product_id='{$row->id}' AND option_value_id='{$row->option_value_id}'";
$mysqli->query($query);
}
Oke, I found my own answer after reading the internet en doing some trail and error.
I created a stored procedure which I will execute on the update trigger.
The trigger
CREATE TRIGGER `order_gereed` AFTER UPDATE ON `oc_order`
FOR EACH ROW IF new.order_status_id = "15"
THEN
CALL VooraadUpdate(new.order_id, new.store_url);
UPDATE push_voorraad SET actie = '1';
END IF
The procedure
CREATE DEFINER=`root`@`localhost` PROCEDURE `VooraadUpdate`(IN `orderID` INT(11), IN `storeURL` VARCHAR(255))
NO SQL
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a, b, c INT;
DECLARE cur1 CURSOR FOR SELECT
oc_order_product.quantity,
oc_order_option.option_value_id,
product.id
FROM oc_order_product
JOIN oc_order_option
ON oc_order_option.order_id = oc_order_product.order_id
JOIN product
ON product.oc_product_id = oc_order_product.model
WHERE oc_order_product.order_id = orderID AND oc_order_product.store_url = storeURL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO a, b, c;
IF done THEN
LEAVE read_loop;
END IF;
UPDATE product_option_value SET quantity = quantity - a WHERE product_id=c AND option_value_id=b;
END LOOP;
CLOSE cur1;
END