0

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.

This is 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 this code:

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

1 Answer 1

1

The JSON index starts from 0. So set:

SET i = 0;
WHILE (i < JSON_LENGTH(images)) DO
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate. Worked really well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.