PHP MySQL从以前的结果中插入新行

时间:2014-01-04 10:55:32

标签: php foreach insert mysqli get

我有一个活动网站,我正在尝试创建一个脚本,向所有参加的成员发送提醒。这是通过从出勤表中选择所有成员并为每个结果记录添加消息来完成的。我目前的代码不起作用。这是代码:

$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);
}

3 个答案:

答案 0 :(得分:2)

试试这段代码。

您需要删除foreach并在while循环内移动插入查询。

$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);
}

答案 1 :(得分:2)

试试这个......你不需要另外一个循环来插入,而抓取你可以插入

$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);
}

答案 2 :(得分:1)

<?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);
}
?>