How to create PHP array from MySQL data - php

I have a database with a column "regId" in a table users
What I want to do is select all rows but only that column (SELECT regId FROM users)
However, in PHP, I want this as
Array("the first row ID", "the second row ID", and so on)
I am building an app using the Google Cloud Messaging and the registration IDs are needed in an array like "Array("something", "something else")
Here's my code
<?php
session_start();
require_once("global.php");
$qry = "SELECT `regId` FROM `users` WHERE regId IS NOT NULL"; //Here's where the IDs are
$fetchQry = mysqli_query($connection, $qry);
// Replace with the real server API key from Google APIs
$apiKey = "/////";
// Replace with the real client registration IDs
$registrationIDs = array("","","",""); //heres how they need the IDs
// Message to be sent
$message = "somethinnnnnn";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'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);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
?>
And I have checked similar questions and they all use a while loop such as
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
However, if I set the $registrationIDs variable equal to $rows or array($rows), it does not work! (even echoing them doesn't show the data)

I ended up sussing it out. Thanks to Create PHP array from MySQL column
Here's what I did:
$column = array();
while($row = mysqli_fetch_array($result)){
$column[] = $row['regId'];
//Edited - added semicolon at the End of line.1st and 4th(prev) line
}
I did earlier try this however it was originally mysql and not mysqli!!
I then also set my $registrationIDs variable equal to $column

try this one:
$rows = [];
while($row = mysqli_fetch_array($fetchQry)) {
$rows[] = $row;
}
see if it can work.

Related

PHP notification functions incorrectly if over a certain number of users

The following code works for 2 or 3 users as long as I limit my query to 3 people. When I try it for 2000 people it no longer sends a notification. I also receive success:0 in response.
public function send_notification($registatoin_ids, $message) {
// Set POST variables
$googleapikey="AIzaSyCeFfqiRt3xFzZH2XDwICJDZkasF7uWBJI";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $googleapikey,
'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);
$result1=json_decode($result);
}
I'm also using the function above to call the function below to send my notifications. My problem is, It works when there are just 2 or 3 users, but when user's exceed 2000 it does not work as expected(sends notifications).
$qry = mysql_query("SELECT deviceToken FROM app_devices");
$devices = array();
while($row = mysql_fetch_assoc($qry))
{
$devices[] = $row['deviceToken'];
}
$gcm->send_notification($devices, $message);
To my knowledge we can at max send 1000 notifications from GCM at a time, so if u want to send more than that, divide the no of users into group of 1000 and send request in that manner.
For Eg:
If u want to send 2000 notifications then make 2 calls each having ids of 1000 users.
I advise you to use Firebase Cloud Messaging because it is the evolution of Google Cloud Messaging.
Try to use this:
$message = array ("message" => $bodyMail, "to" => $to, "From" => $from);
$id = array($to);
$message_status = sendPushNotification( $message, $id );
echo $message_status;
// Send push notification via Firebase Cloud Messaging
function sendPushNotification( $data, $ids )
{
// Insert real FCM API key from the Google APIs Console
$apiKey = "YourApiKey";
// Set POST request body
$fields = array(
'registration_ids' => $ids,
'data' => $data
);
// Set CURL request headers
$headers = array(
'Authorization: key =' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt( $ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
// Set request method to POST
curl_setopt( $ch, CURLOPT_POST, true );
// Set custom request headers
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
// Get the response back as string instead of printing it
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Set JSON post data
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Actually send the request
$result = curl_exec( $ch );
// Handle errors
if ( curl_errno( $ch ) )
{
echo 'FCM error: ' . curl_error( $ch );
}
// Close curl handle
curl_close( $ch );
// Debug GCM response
return $result;
}

Sending gcm to multiple users at a time from mysql database

I'm developing an app and I'm on the final face where registered devices in the database are to receive push notifications at a time.
Currently, with the script I have, it can only send to one device. I have a table in my database called devices and the field that saves the device ID is called device_id. Please any help on how to send to multiple users?
<?php
$message = $_POST['title'];
$id = $_POST['id'];
// Replace with the real server API key from Google APIs
$apiKey = "AIzaSyDn9RPYmnlbs9*****WHKksz73klOqxM";
// Replace with the real client registration IDs
$registrationIDs = array("APA91bHhTiGeAKgphENoGH6********Blw9PspLCPAiprTSDN6mRuW3k253PZyppxgJaqPftTzYZOiWPt5C4XFVmkuqjbXp7MV3mAmpDAYM-11LdIdU0");
// Message to be sent
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message,"title" => "Today's Devotion","id" => $id),
);
$headers = array(
'Authorization: key=' . $apiKey,
'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);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
//echo $result;
//print_r($result);
//var_dump($result);
?>
Fetch all the device ids from your database as below:
$registrationIDs = array();
$query = "select device_id from devices";
while($row = $db->database_fetch_assoc($query))
{
$registrationIDs[] = $row;
}
Now pass this array to the $field array.
create your query to get device ids in $registrationIDs and send all to server.
// Replace with the real client registration IDs
$registrationIDs = array("APA91bHhTiGeAKgphENoGH6********Blw9PspLCPAiprTSDN6mRuW3k253PZyppxgJaqPftTzYZOiWPt5C4XFVmkuqjbXp7MV3mAmpDAYM-11LdIdU0");

Improving php page for sending Notifications to Android Devices

It Send Notification to android devices registered in the mysql database. this is the php code i'm using. and it's working well as far as i can tell.
<?php
$con = mysql_connect("*******.*****.com","*******","*********");
mysql_select_db("*******",$con);
$result1 = mysql_query("SELECT Device_ID FROM Registered_Users") or die(mysql_error());
$api_key = "***************-***********";
$response["products"] = array();
while ($row = mysql_fetch_array($result1))
{
$reg_id = array($row['Device_ID']);
$registrationIDs = $reg_id;
$message = $_POST['msg'];
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registrationIDs,'data'
=> array( "message" => $message ),);
$headers = array('Authorization: key='
. $api_key,'Content-Type: application/json');
$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_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
}
echo "success";
?>
my question is : how can i improve this code to get the best performance " results " possible ?
use this way........
<?php
$con = mysql_connect("*******.*****.com","*******","*********");
mysql_select_db("*******",$con);
$result1 = mysql_query("SELECT Device_ID FROM Registered_Users") or die(mysql_error());
while ($row = mysql_fetch_array($result1))
{
$reg_id[] = $row['Device_ID'];
//from this way you dont need to run function again and again......
}
$api_key = "***************-***********";
$response["products"] = array();
$registrationIDs = $reg_id;
$message = $_POST['msg'];
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registrationIDs,'data'
=> array( "message" => $message ),);
$headers = array('Authorization: key='
. $api_key,'Content-Type: application/json');
$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_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
echo "success";
?>
this will increase code performance....may this will help you
You should send one curl request which includes an array of registration_ids. Doing this will use less resources as it only has to connect to Google's servers in one step rather than sending off several requests. You can just send one request to handle many notifications.
You should also be using something other than mysql_* to interact with your database, for example PDO:
<?php
$dbName = '*****';
$dbUsername = '*****';
$dbPassword = '*****';
$api_key = "***************-***********";
$url = 'https://android.googleapis.com/gcm/send';
$message = $_POST['msg'];
$pdo = new PDO('mysql:host=localhost;dbname=' . $dbName, $dbUsername, $dbPassword);
$stmt = $pdo->query("SELECT Device_ID FROM Registered_Users");
$dbResults = $stmt->fetchAll();
$stmt->closeCursor();
$regIds = array_map(function (array $dbResult) {
return $dbResult['Device_ID'];
}, $dbResults);
$fields = array(
'registration_ids' => $regIds,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $api_key,
'Content-Type: application/json'
);
$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_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo "success";

GCM return error: field data must be a json array

When I using GCM, I got an error return as: field "data" must be a JSON array. Any one have some idea of how to solve it? Thank you.
There is first part of my code, parts of code are omitted:
<?php
$gcm_regid = array();
$gcm_data = array();
while ($row = mysql_fetch_array($result)) {
array_push($gcm_regid, $single_gcm_regid );
array_push($gcm_data , $notificationMessage);
}
?>
Here are the second part:
<?php
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = '******************************';
$registrationIDs = $gcm_regid;
$data = $gcm_data;
$fields = array('registration_ids' => $registrationIDs,
'data' => $data);
//http header
$headers = array('Authorization: key=' . $apiKey,
'Content-Type: application/json');
//curl connection
$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_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;
?>
Change from line 5 of your code
$message = $gcm_data;
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array("message" =>$message)
);
Use json_encode on your $fields object to return a JSON representation.
Look at the accepted answer here to see how it's used.

Invoke a php script as a new record inserted into db

I am just creating a web service for push notification. I Here is my code -
<?php
// gcm api KEY FOR PUSH NOTIFICATION
define( 'API_ACCESS_KEY', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456' );
// CONNECT DB
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
$selected = mysql_select_db("bdname" ,$dbhandle) or die(mysql_error());
$query4=mysql_query("SELECT * FROM `table_name` ORDER BY id DESC LIMIT 0,1");
$row1=mysql_fetch_array($query4);
// static gcm registration id
$reg = 'APA91bF-A97EurJz7IlGFD85cBIWGPCJv7UhV1j19sp6nKEH-9He1GOZQ9ZPegqYmVw3q2OA-_XPpePQckr5o97s9wTTbzYjornXCOqcR3jmN1t1aHV8i4CfRZOWuBDXTixzA3JDnzleHVY3xCtHev8tG90ife05Pw';
$registrationIds = array($reg);
$title=$row1['title'];
$number=$row1['number'];
$id=$row1['id'];
$created_at=$row1['created_at'];
$mes1 = $id .',' . $title . ',' . $number .',' . $created_at;
$message = str_replace('""','',$mes1);
$mes = $message;
$message = array("price" => $mes);
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIds,
'data' => $message,
);
$headers = array(
'Authorization: key=' . API_ACCESS_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);
echo $result;
//}
mysql_free_result($query4);
mysql_close($dbhandle);
?>
I just want if any new row inserted into table, this script will automatic invoke and send notification on given gcm registration id. How can i do this. Is there any php function to do this??
Please help.
Thanks in advance.
Please use this php method to send GCM notification
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Refer these links for detailed tuts on GCM implementation with php
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
http://distriqt.com/post/1273

Categories