I am having this script to send a push notification to a single user.
I want to make a loop in the script to send the notification to ALL users.
I must get the tokens from the database and loop for each one.
<?php
require "init.php";
$message=$_POST['message'];
$title=$_POST['title'];
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
$server_key="MY_SERVER_KEY";
$sql="select * from fcm_info"; //there's one field called fcm_token
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_row($result);
$key=$row[0];
$headers= array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
$fields= array('to'=>$key,
'notification'=>array('title'=>$title,'body'=>$message));
$payload=json_encode($fields);
$curl_session= curl_init();
curl_setopt($curl_session,CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST, true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS, $payload);
$result=curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);?>
What I have tried is:
while($d=mysqli_fetch_array($result,MYSQLI_BOTH))
{
echo $d[0];
}
and I changed:
$key to $d[0];
But it didn't work,
Any suggestions, please.
//Updated
- I am getting only one token but I got two in the database
- MySQLi error
Check it: Result
//Riggs is this my update:
I used to test your code and no error has shown up.
I added echo $row['fcm_token']; after the while loop but the page is not displaying my echo.
The notification has been sent to the first row of fcm_token in the database. I think Riggs that the loop isn't fetching the second row and it isn't setting the $key
to the new token.
Can u have a way to simply do:
- Getting the first-row token value
- setting the $key to the token
- Counter ++
- Getting the second-row token value
//do same steps