Pasindu Dineth Peiris :
I wrote a stored procedure to insert multiple values to same table using an array and a loop. But the table only have the last value of the array. and also it is throwing an error saying "column can't be null." below will be my stored procedure.
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_images`(
packageName VARCHAR(300),
packageUniqueCode VARCHAR(100),
packageAddedDate DATE,
packagePrice DOUBLE,
packageDescription VARCHAR(3000),
packageOwnerID INT,
images VARCHAR(500)
)
BEGIN
declare i INT default 0;
START TRANSACTION;
INSERT INTO packages(packageName, packageUniqueCode, packageAddedDate, packagePrice, packageDescription, packageOwnerID)
VALUES(packageName, packageUniqueCode, packageAddedDate, packagePrice, packageDescription, packageOwnerID);
SET i = 1;
WHILE i <= JSON_LENGTH(images) DO
INSERT INTO packageImages(imageName, location, packageOwnerID, packageID)
VALUES(JSON_EXTRACT(images,CONCAT( '$[', `i`, '].imageName')), JSON_EXTRACT(images,CONCAT( '$[', `i`, '].location')), packageOwnerID,LAST_INSERT_ID());
SET i = i + 1;
END WHILE;
COMMIT;
END
And i'm calling it using below.
CALL insert_images("PJKG", "codea", "2022-11-11", 12, "description", 22, '[{"imageName": "pasinduImage", "location": "uploads/image"},{"imageName": "pasinduImage2", "location": "uploads/image"}]');
Please help me to figure things out. Thanks
slaakso :
The JSON index starts from 0. So set:
SET i = 0;
WHILE (i < JSON_LENGTH(images)) DO