The following is a stored procedure that inserts one record into product_size each time you call the procedure. The procedure takes input parameters for product.id and size.id.
DELIMITER //
CREATE PROCEDURE INSERT_product_size(
IN productID int,
IN sizeID int
)
BEGIN
INSERT INTO
product_size
(product_id, size_id)
VALUES
(productID, sizeID);
END //
DELIMITER ;
This procedure takes a single product id and an "array" of size id's (in the form of a comma-delimited string) and inserts all sizes for the product in one procedure call:
DROP PROCEDURE IF EXISTS INSERT_product_sizes;
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS INSERT_product_sizes(
IN productID int,
IN sizeIDs varchar(100)
)
BEGIN
DECLARE delimiterCount int;
DECLARE sizeID int;
DECLARE loopCount int;
/* Remove spaces, if any, from input string */
SET sizeIDs = REPLACE(sizeIDs, ' ', '');
/* Determine how many commas are in input string */
SET delimiterCount = LENGTH(sizeIDs) - LENGTH(REPLACE(sizeIDs, ',', ''));
SET loopCount = 1;
/* For each id in input string */
WHILE loopCount <= delimiterCount + 1 DO
SET sizeID = SUBSTRING_INDEX(sizeIDs, ',', 1);
INSERT INTO
product_size
(product_id, size_id)
VALUES
(productID, sizeID);
/* Remove last used id from input string */
SET sizeIDs = REPLACE(sizeIDs, CONCAT(sizeID, ','), '');
SET loopCount = loopCount + 1;
END WHILE;
END //
DELIMITER ;