Gcm message not sent to more that 1000 users - php

Gcm message not sent to more that 1000 users , gcm has its own limit of sending message to 1000 users so the idea is to divide the users in batch of 1000 each i tried that but the gcm message is received by first 1000 users only how can we send the message in batches of 1000 each, in a total of say 5000 users, so that all users get the message i am new to php please explain the working
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//echo json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
}
$pushStatus = '';
function getGCMCount(){
$total = "";
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
return $total;
}
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
//echo $i . "</br>" ;
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$pushStatus = array();
//echo "</br> counnt of messages send is". count($pushStatus);
foreach($gcmRegIds as $key=>$val)
{
$message = array('price' => $pushMessage);
//$message1 = array($key=>$val);
//$c = (array_merge($message ,$message1 ));
$pushStatus[] = sendPushNotification($val, $message);
//echo $key;
}
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php //echo $pushStatus . "<br>"?></h3></p>
</form>
</body>
</html>

Refer this snippet for sending messages to more than 1000 users
<?php
//Sample for sending notification to more than 1000 users
$mPushNotification = $push->getMessage();
$stmt = $this->con->prepare("SELECT gcm_regid FROM gcm_users");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
$firebase = new Firebase();
$total = count($tokens);
$groups = ceil($total/800);
$currentval=ceil($total/$groups);
$firebase = new Firebase();
for ($i=0; $i <$groups; $i++) {
$val=($i*$currentval)+1;
$total = ($i+1)*$currentval;
$resToken = getSpecificToken($val,$total);
$result1 = $firebase->send($resToken, $mPushNotification);
}
function getSpecificToken($upper,$lower)
{
$stmt = $this->con->prepare("SELECT * FROM gcm_users LIMIT $upper,$lower");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
return $tokens;
}
function getMessage() {
$res = array();
$res['data']['id'] = 1;
$res['data']['title'] = "TestTitle";
$res['data']['message'] = "TestMessage : Hello";
return $res;
}
?>
//Firebase File
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actual curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
?>

Related

How can I insert single data using implode and explode

I want to insert single data into SQL. I have instert table and first and lastname I will post data to service.php using implode and in service I will exlope data and add into a database. But it doesn't work.
Here is my inser.php page
if($_POST)
{
$first_name = ($_POST['first_name']);
$last_name = ($_POST['last_name']);
$query=$first_name.'|'.$last_name;
$params=array(
'action' => "INSERTSINGLE",
'query' => $query
);
$postData='';
foreach($params as $k => $v){
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
if(is_array($postData)){
$count=count($postData);
}else{
$count=0;
}
print_r($postData);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL,"service.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER,false);
curl_setopt($ch, CURLOPT_POST,$count);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/json'));
$responsedata=curl_exec($ch);
curl_close($ch);
print_r($responsedata);
}
and here is my webservice page
require_once('index.php');
$action=$_POST["action"];
echo $action;
$query = $_POST["query"];
$gelendata=explode('|',$query);
$firstname=$gelendata[0];
$lastname=$gelendata[1];
switch ($action)
{
case 'GETCLIENTS':
echo $firstname;
$query = $myPDO->query("SELECT * FROM users",PDO::FETCH_ASSOC);
foreach ($query as $row) {
echo $row['first_name']."-".$row['last_name']."<br />\n";
}
break;
case 'GETCLIENT':
echo 'client çekildi.';
$query = $myPDO->query("SELECT * FROM users WHERE user_id='{$query}'")->fetch(PDO::FETCH_ASSOC);
print_r($query);
break;
case 'INSERTSINGLE':
echo 'client çekildi.';
$query = $myPDO->query("INSERT INTO users (firs_name,last_name) VALUES({$firstname},{$lastname})")->fetch(PDO::FETCH_ASSOC);
print_r($query);
break;
I can take the data but I can not insert. Can you please forward me? Thanks...
case 'INSERTSINGLE':
echo 'client çekildi.';
$query = $myPDO->query("INSERT INTO users (firs_name,last_name) VALUES('{$firstname}','{$lastname}')")->fetch(PDO::FETCH_ASSOC);
print_r($query);
break;

Select Conditional SQL Statement

I am posting data to a URL to send a Thank You Message. The details am picking are from a table called readtextfilejson. From where I am sending Thank you messages to users.
I am however not able to select details of the only users who haven't received their text message. My code is selecting all the data and posting to all the users again and again in a loop. Thus sending multiple ThankYouMessages to users.
I have added a new column called ThankyouMessage that is by default = 'not sent'.
So that when my script runs, it updates the ThankYouMessage column to = 'SENT', so that my script can Only select details of users who haven't yet received their thankyoumessage.
Thus i don't keep re-sending the same message again and again. Kindly take a look at my script below and assist how i might resolve this.
My table structure:
<?php
$data = (string) file_get_contents($file);
//echo $data;
$data = str_replace('//Confirmation Respose', '', $data);
$data = str_replace('// Validation Response', '', $data);
$data = str_replace(' ', '', $data);
$data = preg_replace('/\s+/S', " ", $data);
$data = trim($data);
$pattern = '/\s*/m';
$replace = '';
$testString = $data;
$removedWhitespace = preg_replace( $pattern, $replace,$testString );
$removedWhitespace2 = str_replace (' ', '', $testString);
$getAllData = explode('}{', $removedWhitespace2);
foreach ($getAllData as $row) {
$row = str_replace('{', '', $row);
$rowData = explode(',"', $row);
$rowData = explode(',"', $row);
$columnValues = array();
$chkTransId = '';
foreach ($rowData as $value) {
$newVal = explode(':', $value);
$key = str_replace('"', '', $newVal[0]);
$val = str_replace('"', '', $newVal[1]);
$val = trim($val);
$columnValues[] = ($val) ? "'$val'": "''";
if($key == 'TransID'){
$chkTransId = $val;
}
}
if($chkTransId == ''){
continue;
}
////THIS IS THE SECTION AM HAVING PROBLEMS WITH - I WANT TO
////SELECT ONLY THE DATA WHERE THE COLUMN WHERE thankyoumessage =
///// 'NOT SENT'
$chkSql = "select * from `readtextfilejson`where TransID='$chkTransId'";
$getResult = mysqli_query($con, $chkSql);
$getCount = mysqli_num_rows($getResult);
$row = mysqli_fetch_object($getResult);
$text = "Dear ". $row->FirstName ." Your Payment of ". $row->TransAmount ." to XXXXX was Received Succesfully. Confirmation Code: ". $row->TransID ."";
$destination = array("messageId"=>"$product_id","to"=>"$row->MSISDN");
$product_id=uniqid();
$notifyUrl = "URL";
$notifyContentType = "application/json";
$callbackData = 'eHostOnlineCodeCheck125690';
$username = "USERNAME";
$password = "PASSWORD";
$postUrl = "POSTURL";
$message = array("from" => "USERNAME",
"destinations" => $destination,
"text" => $text,
"bulkId" => "",
"notifyUrl" => $notifyUrl,
"flash" => "false",
"notifyContentType" => $notifyContentType,
"callbackData" => $callbackData);
$postData = array("messages" => array($message));
$postDataJson = json_encode($postData);
//Submit all data to SMS server
$ch = curl_init();
$header = array("Content-Type:application/json", "Accept:application/json");
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// response of the POST request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$responseBody = json_decode($response);
curl_close($ch);
echo "<pre>";
print_r($row);
print_r($responseBody);
echo "</pre>";
$Sql = "UPDATE readtextfilejson SET thankyoumessage = 'SENT' WHERE thankyoumessage = 'not sent'";
mysqli_query($con, $Sql) or die(mysqli_error($con));
if($getCount > 0){
continue;
}
$columnValues = implode(',', $columnValues);
$sql = "INSERT INTO `readtextfilejson`(`TransactionType`, `TransID`, `TransTime`, `TransAmount`, `BusinessShortCode`, `BillRefNumber`, `InvoiceNumber`, `OrgAccountBalance`, `ThirdPartyTransID`, `MSISDN`, `FirstName`, `MiddleName`, `LastName`) VALUES (".$columnValues.")";
mysqli_query($con, $sql) or die(mysqli_error($con));
}
echo 'Data inserted successfully';
?>
2 possible issues.
1) You are selecting the transaction regardless of what thankyoumessage is set to. You may need to add a condition to that first SQL's where clause
SELECT * FROM `readtextfilejson`
WHERE TransID = '$chkTransId' AND thankyoumessage = 'not sent'
2) When you update the transaction thankyoumessage to "SENT" you are setting all transactions, because your update statement is missing the transaction id. You may need to add it.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE thankyoumessage = 'not sent' AND TransID = '$chkTransId'
And since you want to set it to SENT regardless of what it was before, you may not need the thankyoumessage check either.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE TransID = '$chkTransId'

Parse error: syntax error, unexpected '(', expecting '{' in C:\wamp\www\NewFirebase\Firebase.php on line 3

sent push notification using Firebase via PHP API.Parameter pass from the android and data get to push notification sent to android. Announcement get data from the database and its pass data in Firebase class and its sent to notification in android.in line 3 whats error i don't Know.
Announcement.php
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
// $full_name = $_POST['full_name'];
// $contact_number = $_POST['contact_number'];
require_once __DIR__ . '/firebase.php';
require_once __DIR__ . '/push.php';
$firebase = new Firebase();
$push = new Push();
$reg = $_GET['reg'];
$fdate = $_GET['fdate'];
$tdate = date('Y-m-d G:i:s');
//$tdate = date("2018-01-20");
print_r($tdate);
$date2 = strtotime("+1 day", strtotime($fdate));
$fdate1 = date("Y-m-d", $date2);
//print_r($fdate1);
require_once('Demo.php');
$sql = "select max(AnnounceDate) as announcedate from AnnouncementTable";
$stmt1 = sqlsrv_query($conn,$sql);
$result = array();
$result["announcement"] = array();
$result["success"] = 1;
$row = sqlsrv_fetch_array($stmt1,SQLSRV_FETCH_ASSOC);
$date1 = $row["announcedate"]->format('Y-m-d');
$marks = array();
$marks["announcedate"] = $row["announcedate"]->format('Y-m-d');
array_push($result["announcement"], $marks);
echo json_encode($result);
print_r($date1);
if ($date1 != $fdate){
$check = "select * from
AnnouncementTable
where
AnnounceDate between '$fdate1' and '$tdate';select token from Std_Reg where RegNo='$reg'";
$stmt = sqlsrv_query($conn,$check);
if(sqlsrv_has_rows($stmt) > 0){
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)){
$notiTitle = "Eurasian Infotech";
$clickEvent ="Announcement";
$notiMessage = $row["Title"];
$notiDescription = $row["Description"];
$regId = $row['token'];
$push->setTitle($notiTitle);
$push->setMessage($notiMessage);
$push->setClickevent($clickEvent);
$push->setAnnounce($notiDescription);
$json = '';
$response = '';
$json = $push->getPush();
$response = $firebase->send($regId,$json);
//sendNotification($notiTitle, $notiMessage,$reg,$date1);
echo "sucessfully added";
}
}else{
echo "error in sending request";
}
}else{
echo "Sent Notification";
}
}else{
echo 'error';
}
?>
Firebase.php
<?php
class Firebase(){
public function send($to,$message){
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
private function sendPushNotification($fields) {
require_once __DIR__ . '/config.php';
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
}
?>
push.php
<?php
class Push{
private $title;
private $message;
private $date;
private $announce;
private $clickevent;
function _construct(){
}
public function setTitle($title){
}
public function setMessage($message){
}
public function setDate($date){
}
public function setAnnounce($announce){
}
public function setClickevent($clickevent){
}
public function getPush(){
$res = array();
$res['data']['title'] = $this->title;
$res['data']['message'] = $this->message;
$res['data']['date'] = $this->date('Y-m-d');
$res['data']['announce'] = $this->announce;
$res['data']['clickevent'] = $this->clickevent;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
?>

PHP curl automatically sending two requests

Im Using PHP curl for saving website name page name on which user has just clicked and ip address in my database, but the problem curl send 2 requests automatically one with correct data and in other one just changed the page name to index.php, i want to abort the second request just, means when curl executes one time then no request by curl untill an other click on the same page, hope my discription will help you to find out my error for me, here is my code.
**This IS My Curl Code**
$wb_nm = $_SERVER[HTTP_HOST];
$pg_nm = $_SERVER[PHP_SELF];
$usr_ip = $_SERVER[REMOTE_ADDR];
$pg_nm_ultr = trim($pg_nm , '/');
$n_url = "localhost/curl/new_page.php";
$data = array(
"varhost" => $wb_nm,
"varpage" => $pg_nm_ultr,
"varip" => $usr_ip
);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $n_url);
curl_setopt($post, CURLOPT_POSTFIELDS, $data);
curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
$result = curl_exec($post);
curl_close($post);
?>
**And This Is new_page.php**
if(isset($_POST['varhost']) && isset($_POST['varpage']) && isset($_POST['varip']))
{
$web_name = $_POST['varhost'];
$page_name_ulter = $_POST['varpage'];
$user_ip = $_POST['varip'];
define("DB_HOSTNAME", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_DB", "pan");
$connection = mysqli_connect(DB_HOSTNAME, DB_USER, DB_PASS, DB_DB);
if(isset($connection)){
$query = "SELECT * FROM tbl_agencies WHERE weblink = '".$web_name."'";
$result = mysqli_query($connection , $query);
if($result){
while($row = mysqli_fetch_array($result)){
if(isset($row))
{
$D_id = $row['domain_id'];
$D_name = $row['website'];
if($D_id == 0)
{
return false;
}
}
else
{
}
break;
}
}
}
$date_date = date('Y-m-d');
$time_stamp = date("H:i:s");
$query_Code = "INSERT INTO user_details (website_domain_id , website_domain_name , page_clicked , user_IP , access_date , access_time) VALUES ('".$D_id."','".$D_name."' , '".$page_name_ulter."' , '".$user_ip."' , '".$date_date."' , '".$time_stamp."')";
$result_Code = mysqli_query($connection , $query_Code);
if($result_Code)
{
mysqli_close($connection);
}
}
?>
In curl_setopt($post, CURLOPT_POSTFIELDS, $fields);, you can send fields as an associative array. So this code:
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
is actually not needed such that curl_setopt($post, CURLOPT_POSTFIELDS, $fields); becomes
curl_setopt($post, CURLOPT_POSTFIELDS, $data);

convert data to JSON array

i am trying to use the push notification in google cloud messages and i am passing an array om registration ids, but for some reason i got the following error:
Field "data" must be a JSON array: You have just invited to play 'Soccer'
this is the part that i am trying to pass:
"registred_ids":["APA91bF9itasGCSK8NbD9u5GJWnEmbWCdS0sEn_xxRVbVpfI0_3FKkvxVBr5xtdE26VZgOO8rCBpf4CaAzHUbMj7PmmDxqpdbWO6VBrPB8dW4CPqPovJbnB_p1Ha_fuwyf8SnOqgOFajK8HEdiZO65qUljO2wCuuDQ"]
not the code of the gcm is :
<?php
class GCM {
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once 'connection.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' .GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
and the code which passing the registration ids is:
<?php
include 'response_process.php';
include 'gcm.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(manager_id,kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,current_participants,scheduled,event_status)
VALUES ('$manager','$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','1','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$query_users = "SELECT id,gcm_id From users WHERE ";
$i=0;
$size_of_param = (count($json));
foreach($json as $user) {
if ($i < $size_of_param - 1)
// add a space at end of this string
$query_users .= "users.mobile = '".$user."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
$event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$insert_query = "INSERT into attending (event_id,user_id,status) VALUES ";
$i=0;
$status = "deny";
$registration_ids = array();
while($row_user = mysqli_fetch_assoc($event_user_s_res))
{
$registration_ids[$i]=$row_user["gcm_id"];
if($i<$size_of_param - 1)
$insert_query .= "('" .$event_id. "','" .$row_user["id"]. "','" .$status. "'), ";
else
$insert_query .= "('".$event_id."','".$row_user["id"]."','".$status."') ";
$i++;
}
$insert_query_res = mysqli_query($dblink,$insert_query) or die (mysqli_error($dblink));
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}else{
$output["id_query"]= $insert_query;
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$message = "You have just invited to play '".$sport."'";
$output["gcm_message"]=$message;
$gcm_res = $gcm->send_notification($registration_ids,$message);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
} // if $no_of_rows < 1
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
Use this-
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => array("message" => $message),
);
It says the data field needs to be an array, but you are setting it to $message, which is a string, not an array.
Field "data" must be a JSON array: You have just invited to play 'Soccer'
This means the value passed in data node is not a json.
Encoding $message into json will fix the error.

Categories