You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP结合MySQL操作时如何向外键关联表插入多条数据?

错误原因

你遇到的语法报错是因为不能将PHP循环逻辑直接写在SQL字符串中,字符串内容只会被当做普通文本解析,不会执行内部的PHP代码。同时你的代码还存在数组变量插值语法错误、括号未闭合等问题。

最优解决方案:直接使用INSERT ... SELECT语法

不需要在PHP层做循环查询插入,直接用一条SQL即可完成需求,性能更高且避免SQL注入风险:

// 对变量做转义处理,避免SQL注入
$univuid = mysqli_real_escape_string($con, $univuid);
$sql = "INSERT INTO `user_notification` (`notif_id`, `user_id`)
        SELECT `id`, '{$univuid}' FROM `notification` WHERE `noti_user` = 'Pro'";
$query = mysqli_query($con, $sql);

备选方案:PHP层循环插入(适合需要额外逻辑处理的场景)

如果需要在插入前对数据做额外处理,推荐使用预处理语句,避免SQL注入和语法错误:

// 查询符合条件的通知ID
$notice = "SELECT id FROM notification WHERE noti_user ='Pro'";
$noticeqry = mysqli_query($con, $notice);

// 预处理插入语句
$stmt = mysqli_prepare($con, "INSERT INTO `user_notification` (`notif_id`, `user_id`) VALUES (?, ?)");
// 绑定参数,i对应int类型的notif_id,s对应字符串类型的user_id,可根据实际字段类型调整
mysqli_stmt_bind_param($stmt, "is", $notifId, $univuid);

// 循环执行插入
while($noticerow = mysqli_fetch_assoc($noticeqry)){
    $notifId = $noticerow['id'];
    mysqli_stmt_execute($stmt);
}

// 关闭预处理语句
mysqli_stmt_close($stmt);

补充说明

如果需要插入的数据量较大,可以拼接多值INSERT语句减少数据库交互次数:

$noticeqry = mysqli_query($con, "SELECT id FROM notification WHERE noti_user ='Pro'");
$values = [];
$univuid = mysqli_real_escape_string($con, $univuid);
while($row = mysqli_fetch_assoc($noticeqry)){
    $id = (int)$row['id'];
    $values[] = "($id, '$univuid')";
}
if(!empty($values)){
    $sql = "INSERT INTO `user_notification` (`notif_id`, `user_id`) VALUES " . implode(',', $values);
    mysqli_query($con, $sql);
}

内容的提问来源于stack exchange,提问作者Satyanarayan Bhuniya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:45:02