How to loop through an array and execute a query within the loop in a store procedure in MySQL

Viewed 30

I would like to embed a query in a stored procedure. The query to be embedded, however, is carried out within a foreach cycle because the values are transmitted from a form.

This is the snippet, in PHP:

<?php

foreach ($preferences as $preference) {

  $sth = $db->prepare('INSERT INTO preferences (preference, user_cod) values (:preference, :user_cod)');
  $sth->bindValue(':preference', $preference);
  $sth->bindValue(':user_cod', $user_cod);
  $sth->execute();

}

?>

How can I pass the array as a parameter to the stored procedure to execute the same query several times within the foreach loop in the stored procedure?

To give an example, the stored procedure would be structured like this:

BEGIN

  INSERT INTO users (name, surname) values (name_in, surname_in);

  INSERT INTO images (image, user_cod) values (image_name_in, user_cod_in);

  FOREACH preferences AS preference

    INSERT INTO preferences (preference, user_cod) values (preference_in, user_cod);

  END FOREACH;

END
0 Answers
Related