user3129227
user3129227

Reputation: 51

PHP MySQL Insert new rows from previous result

I have a site for events and I'm trying to create a script that sends an alert to all members who are attending. This is done by selecting all of the members from the attendance table and adding a message for each of the resulting records. The code that I have at the moment is not working. Here is the code:

$get_attendance_sql = "SELECT attendee FROM attendance WHERE event = '$event_id'";
$get_attendance_res = mysqli_query($con, $get_attendance_sql);
while($row = mysqli_fetch_assoc($get_attendance_res)){
    $event_memberid = $row["attendee"];
}

foreach($row)
{
    $insert_membernote_sql = "INSERT INTO notes (id, recipient, type, subtype, link, date) VALUES('$id', '$event_memberid', 'cancel', 'event', '$event_id', '$time')";
    $insert_membernote_res = mysqli_query($con, $insert_membernote_sql);
}

Upvotes: 2

Views: 100

Answers (3)

Balaji Kandasamy
Balaji Kandasamy

Reputation: 4506

<?php
$get_attendance_sql = "SELECT attendee FROM attendance WHERE event = '$event_id'";
$get_attendance_res = mysqli_query($con, $get_attendance_sql);
while($row = mysqli_fetch_assoc($get_attendance_res)){
    $event_memberid[] = $row["attendee"];
}

foreach($event_memberid as $memberid )
{
    $insert_membernote_sql = "INSERT INTO notes (id, recipient, type, subtype, link, date) VALUES('$id', '$memberid', 'cancel', 'event', '$event_id', '$time')";
    $insert_membernote_res = mysqli_query($con, $insert_membernote_sql);
}
?>

Upvotes: 1

user1844933
user1844933

Reputation: 3417

Try this... you dont need another loop for insert, while fetching you can insert

$get_attendance_sql = "SELECT attendee FROM attendance WHERE event = '$event_id'";
$get_attendance_res = mysqli_query($con, $get_attendance_sql);
while($row = mysqli_fetch_assoc($get_attendance_res)){

$event_memberid = $row["attendee"];    
$insert_membernote_sql = "INSERT INTO notes (id, recipient, type, subtype, link, date)    VALUES('$id', '$event_memberid', 'cancel', 'event', '$event_id', '$time')";
    $insert_membernote_res = mysqli_query($con, $insert_membernote_sql);
}

Upvotes: 2

Kumar V
Kumar V

Reputation: 8838

Try this code.

You need to remove foreach and move insert query inside the while loop.

$get_attendance_sql = "SELECT attendee FROM attendance WHERE event = '$event_id'";
$get_attendance_res = mysqli_query($con, $get_attendance_sql);
while($row = mysqli_fetch_assoc($get_attendance_res)){
    $event_memberid = $row["attendee"];
    $insert_membernote_sql = "INSERT INTO notes (id, recipient, type, subtype, link, date) VALUES('$id', '$event_memberid', 'cancel', 'event', '$event_id', '$time')";
    $insert_membernote_res = mysqli_query($con, $insert_membernote_sql);
}

Upvotes: 2

Related Questions