Search code examples
phpmysqldatabasebatch-processing

Need to send notification in a batch of 1000


I have created notification application , now i want to send notification to batch of 1000 users, but as i am new i dont know how to create that batch.

this is my code to push notification.

<?php
include('header.php');

define( 'API_ACCESS_KEY', '[API-KEY comes here]' );

$sql="SELECT * FROM user_data";
$result = mysqli_query($conn, $sql) or die ('Error'.mysqli_error($conn));
$registrationIds=array();
while($row=mysqli_fetch_assoc($result)){

    $registrationIds[] = $row['allow'];
}
$ids=json_encode($registrationIds);
$fields = array
(
    'registration_ids'  => $registrationIds
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;


?>

Now i can push notification on to users but how can i send notification in batch of 1000 if i have 10000 users?


Solution

  • Something like this (assuming that you want to send batch of 1000 registration ids with every curl request):

    $batch_size = 1000; // 1000 per request
    
    $iterations = ceil(count($registrationIds) / $batch_size); // determine how many iterations are needed
    
    for ($i = 0; $i < $iterations; $i++) {
        $offset = $i * $batch_size;
        $batch_of_1000_user_ids = array_slice($registrationIds, $offset, $batch_size);
    
        // json_encode, prepare headers and send curl request
    }