Skip to content
Advertisement

Insert repeatedly from foreach loop

I have a problem I’m trying to insert data into a table except that I need to retrieve the id before

  $get_ = $db->prepare("SELECT * FROM  table
                        WHERE id = :id");
  $get_->execute(['id' =>$id]);

  $get_ = $get_->fetchAll();

  foreach ($get_member as $k) {

    $not = "INSERT INTO notifications(..., ..., ...,id)
            VALUES(:..,:...,:...,:id);
    $q = $bdd->prepare($not);

    $q->execute([
        '..' => ,
        'id' => $k['id'] // from foreach loop
    ])

}

I want an insertion as many times as the loop returns the result.

thank you in advance

Advertisement

Answer

Why are you using a loop for something that SQL does natively? You should be using insert . . . select:

INSERT INTO notifications (..., ..., ...,id)
    SELECT :.., :..., :..., t.id
    FROM table t;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement