PHP MySQL 数组中的多行


PHP MySQL Multiple rows from array

我想向我网站上的多个用户发送通知。他们的 ID 在数组 ($userinput) 中。$userinput在每个值的开头保存由逗号分隔的成员 ID(如"7,1,2,3")。

我想运行这样的查询:

$sqlnot = "INSERT INTO lb_notif (to_id, time_sent, from_id, subject, message) VALUES ('$user_id_here', now(), '$logOptions_id', '$title', 'You have been invited to this group chat: <a href=profilechat.php?id=$logOptions_id&chat=$act_item_id>Click here to enter</a>.') ";

我如何才能将其发送给所有这些成员?

您需要循环数组并动态构建查询:

$sqlnot = "INSERT INTO lb_notif (to_id, time_sent, from_id, subject, message) VALUES";
$parts = array();
foreach($userinput as $user) {
    $parts[] = "('$user', now(), '$logOptions_id', '$title', 'You have been invited to this group chat: <a href=profilechat.php?id=$logOptions_id&chat=$act_item_id>Click here to enter</a>.') ";
}
$sqlnot .= implode(',', $parts);
    $id_string = "7,1,2,3";     
    $user_ids = explode(",", $id_string);
    foreach($user_ids as $user_id_here){
         $sqlnot = "INSERT INTO lb_notif (to_id, time_sent, from_id, subject, message) VALUES ('$user_id_here', now(), '$logOptions_id', '$title', 'You have been invited to this group chat: <a href=profilechat.php?id=$logOptions_id&chat=$act_item_id>Click here to enter</a>.') ";
    // execute your query here
    }
如果要

多次插入,则foreach是一个超级按钮选项,如下所示:

$ids = explode(",", $userinput);
foreach($ids as $user_id){
     $sqlnot = "INSERT INTO lb_notif (to_id, time_sent, from_id, subject, message) VALUES ('$user_id_here', now(), '$logOptions_id', '$title', 'You have been invited to this group chat: <a href=profilechat.php?id=$logOptions_id&chat=$act_item_id>Click here to enter</a>.') ";
}