简体   繁体   中英

How to insert more than 1 row into foreign key table in php mysql?

Table1: notification Table2: user_notification

$notice = "SELECT id FROM notification
    WHERE noti_user ='Pro'";
$noticeqry = mysqli_query($con, $notice); 

$sql = "INSERT INTO `user_notification` (`notif_id`, `user_id`) 
  values while($noticerow = mysqli_fetch_array($noticeqry)){("$noticerow['id']", "$univuid"}";
  $query= mysqli_query($con,$sql);

Not working and getting error Parse error: syntax error, unexpected variable "$noticerow"

The INSERT syntax is WAY off, and besides the fact there is SQL injection issues, I believe what you're trying to do is:

while ($noticerow = mysqli_fetch_array($noticeqry)) {
    $sql = "INSERT INTO `user_notification` (`notif_id`, `user_id`)
            VALUES ({$noticerow['id']}, $univuid)";
    mysqli_query($con, $sql);
}

However, I'd strongly advise to shift into using parameterized queries to avoid SQL injection issues, which can replace the above handling with:

$sql = 'INSERT INTO `user_notification` (`notif_id`, `user_id`) VALUES (?, ?)';
$stmt = mysqli_prepare($con, $sql);

while ($noticerow = mysqli_fetch_array($noticeqry)) {
    mysqli_stmt_bind_param($stmt, 'ii', $noticerow['id'], $univuid);
    mysqli_stmt_execute($stmt);
}

Maybe u can try insert through for loop, like bellow..

$notice = "SELECT id FROM notification WHERE noti_user ='Pro'";
$noticeqry = mysqli_query($con, $notice); 
$row = $noticeqry->fetch_assoc();
$count_id = mysqli_num_rows($noticeqry);

for($i=0; $i < $count_id; $i++){

    $noticerow = $row['id'][$i];

    $sql = "INSERT INTO `user_notification` (`notif_id`, `user_id`) values ('$noticerow', '$univuid')";
    $query= mysqli_query($con,$sql);

}

if($quey){echo "New record created successfully";}else{ echo "Error: " . $sql . "<br>" . mysqli_error($con);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM