Home > Software design >  How to insert more than 1 row into foreign key table in php mysql?
How to insert more than 1 row into foreign key table in php mysql?

Time:11-07

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"

CodePudding user response:

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

CodePudding user response:

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);}
  • Related