Foreach insert query the best way

Hi i’ve got this code which works fine but I think it uses a lot of server resources because execute a query to the database for each user id stored in a group, is there any way to solve this problem?
Also I’ve tried to use prepared statement with no luck.

	$event_start_date = date('d-m-Y', strtotime($new_start_date));
        $notification = "Nuovo evento <span class='text-warning'><strong>$event_title</strong></span> inizia il $event_start_date";
        $notification_status = "0";
        $notification_category= "events";


        $sql = "SELECT user_join_id FROM user_group_join WHERE group_join_id='$event_group'";

		$result= mysqli_query($conn,$sql);

		$datas= array();

		if(mysqli_num_rows($result) > 0){

			while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){

			$datas[]= $row;

			}

		}

		foreach($datas as $data) {

		$id_cliente = $data['user_join_id'];

		$event_notification = mysqli_prepare($conn, "INSERT INTO user_notifications (notification_sent_by, notification_sent_to, notification_message, notification_time, notification_status, notification_category, notification_category_id) VALUES(?,?,?,now(),?,?,?)");
		mysqli_stmt_bind_param($event_notification, 'iisisi', $userid, $id_cliente, $notification, $notification_status, $notification_category, $event_id);
		mysqli_stmt_execute($event_notification);
		mysqli_stmt_close($event_notification);

		}

Many thanks for your help

Could you not do something like:

$query = "INSERT INTO user_notifications (notification_sent_by, notification_sent_to, notification_message, notification_time, notification_status, notification_category, notification_category_id) 
SELECT '$userid', $user_join_id, '$notification', NOW(), '$notification_status',  '$notification_category', '$event_id' 
FROM user_group_join WHERE group_join_id='$event_group'";

I don’t know how to convert that into a prepared statement, perhaps in exactly the normal way. The idea is to combine the two queries and have the server do all the work.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.