SQL Query in PHP script doesnt fill table in database - php

In PHP script I parsed some .csv file and trying to execute on a few ways and this is a closest I can get. When I run query manually in database everything is o.k but when I go through the the script I just got New record created successfully and the table stays empty except ID which count how many inserts I got.
o.k that's cool optimization but I still don't getting the data. Yap the $dataPacked is clear below is my whole script can you pls gave some suggestion.
<?php
class AdformAPI {
private $baseUrl = 'https://api.example.com/Services';
private $loginUrl = '/Security/Login';
private $getDataExportUrl = '/DataExport/DataExportResult?DataExportName=ApiTest';
public function login($username, $password) {
$url = $this->baseUrl . $this->loginUrl;
$params = json_encode(array('UserName' => $username, 'Password' => $password));
$response = $this->_makePOSTRequest($url, $params);
$response = json_decode($response, true);
if (empty($response['Ticket'])) {
throw new \Exception('Invalid response');
}
// var_dump($response);
return $response['Ticket'];
}
public function getExportData($ticket) {
$url = $this->baseUrl . $this->getDataExportUrl;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Ticket: '. $ticket
));
$output = curl_exec($ch);
return $output;
}
public function downloadFileFromUrl($url, $savePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
// if (!is_dir($savePath) && is_writable($savePath)) {
$file = fopen($savePath, "w+");
fputs($file, $data);
fclose($file);
// } else {
// throw new \Exception('Unable to save file');
// }
}
private function _makePOSTRequest($url, $json_data) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($json_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
// Login and data download url
$api = new AdformAPI();
$ticket = $api->login('example', '123546');
$exportDataResponseJson = $api->getExportData($ticket);
$exportDataResponse = json_decode($exportDataResponseJson, true);
if (empty($exportDataResponse['DataExportResult']) || $exportDataResponse['DataExportResult']['DataExportStatus'] != "Done") {
throw new \Exception('GetDataExport invalid response');
}
// Download zip
$fileDir = '/var/www/html/app-catalogue/web/export';
$fileName = 'report.zip';
$filePath = $fileDir . DIRECTORY_SEPARATOR . $fileName;
$api->downloadFileFromUrl($exportDataResponse['DataExportResult']['DataExportResultUrl'], $filePath);
// Unzip
$zip = new ZipArchive;
$res = $zip->open($filePath);
$csvFilename = '';
if ($res === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$csvFilename = $zip->getNameIndex($i);
}
$zip->extractTo($fileDir);
$zip->close();
} else {
throw new Exception("Unable to unzip file");
}
// Parse CSV
$csvPath = $fileDir . DIRECTORY_SEPARATOR . $csvFilename;
if (is_readable($csvPath)) {
$dataCsv = file_get_contents($fileDir . DIRECTORY_SEPARATOR . $csvFilename);
$dataArr = explode("\n", $dataCsv);
$dataPacked = array();
foreach ($dataArr as $row) {
$row = str_replace(" ", "", $row);
//$row = wordwrap($row, 20, "\n", true);
$row = preg_replace('/^.{20,}?\b/s', "$0&nbsp", $row);
$row = explode("\t", $row);
$dataPacked[] = $row;
}
}
// SQL Connestion
$servername = "192.168.240.22";
$username = "liferaypublic";
$password = "liferaypublic";
$dbname = "liferay_dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue; }
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//var_dump($dataPacked);

try this - I am assuming you have sanitised the values in $dataPacked.
Note edited to addslashes just in case.
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue;}
foreach ($rowArray as $k=>$v) {
$sanitised = preg_replace("/[^[:alnum:][:space:]]/ui", '', $v);
$rowArray[$k] = addslashes(trim($sanitised));
}
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Related

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;
}
}
?>

Exlpode xml and turn into array

I want to know how to explode or split xml and turn into array and then insert it to database. Because i have an api that need to hit every day and it return xml.
here's my xml sample:
<ArrayOfUnitPrice>
<UnitPrice>
<PriceAmount>1579.7080</PriceAmount>
<PriceDate>2016-09-02</PriceDate>
<PriceType>XWZ</PriceType>
</UnitPrice>
<UnitPrice>
<PriceAmount>1028.4137</PriceAmount>
<PriceDate>2016-09-02</PriceDate>
<PriceType>ABC</PriceType>
</UnitPrice>
...
</ArrayOfUnitPrice>
I'm using this code to extract the xml response:
$ch = curl_init("111.222.333.444:8080/code.asmx/Price");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
//my code here
curl_close($ch);
SOLVED
I already done solve my code by using this code below guys.
$xml = simplexml_load_string($result);
for ($i=0; $i < count($xml) ; $i++) {
$arr[] = array (
'PriceAmount' => $xml->UnitPrice[$i]->PriceAmount,
'PriceDate' => $xml->UnitPrice[$i]->PriceDate,
'PriceType' => $xml->UnitPrice[$i]->PriceType
);
}
$data = json_decode(json_encode($arr), true);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dailywork";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(is_array($data)){
$check = "SELECT * FROM table_unit";
if($conn->query($check)->num_rows > 0){
// my stuff to here :-D
}else{
/*Insert data to DB*/
$sql = "INSERT INTO table_unit (PriceAmount, PriceDate, PriceType) values ";
$valuesArr = array();
foreach($data as $row){
$PriceAmount = $row[PriceAmount][0];
$PriceDate = $row[PriceDate][0];
$PriceType = $row[PriceType][0];
$valuesArr[] = "('$PriceAmount', '$PriceDate', '$PriceType')";
}
$sql .= implode(',', $valuesArr);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
/*End Insert data to DB*/
}
}
$conn->close();
This function will give you an array of your xml
function xml2php($xmlcontent)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xmlcontent, $arr_vals);
xml_parser_free($xml_parser);
return $arr_vals;
}
pass your $result like this and check it
xml2php($result);
let me know if it helps you

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.

Make SOAP request and insert duplicate values on database

I make a soap request in php, and I get the response from request and insert the values of the response in my database. I use my browser to run the script but something strange happens when I copy the link to another tab and run it, because when I check my database the values are duplicate. Sometimes when run the script the values are not duplicate in my database at the moment, but the next day the values are duplicate, and I don't understand why.
soap_request.php
<?php
ini_set('default_charset','utf8');
$init_today = date("Y-m-d");
$xml = 'soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:def="http://****/definitions" xmlns:cul="http:/***/****/***">
<soapenv:Header>'....;
$soapUrl = "https://****/Culture"; // asmx URL of WSDL
$headers = array(
...
"SOAPAction: http://****/****/****/*****",
"Content-length: ".strlen($xml),
);
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
...
$response = curl_exec($ch);
curl_close($ch);
$string = str_replace(array('ns1:', 'ns2:', 'ns3:'), array('', '', ''), $response);
$content = new SimpleXMLElement($string);
$con = mysqli_connect("localhost","root","***","*****");
function insertEventId($con, $content){
$array_id = array();
foreach($content->xpath('//Event') as $header){
$result = ($header->xpath('Id'));
$event_id = (string) $result[0];
$sql = "INSERT INTO eventos_sapo (event_id) VALUES ('$event_id')";
if (mysqli_query($con, $sql)) {
echo $sql . "</br>";
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
array_push($array_id, $event_id);
}
return $array_id;
}
function insertTitulo($con, $content, $array_id){
$count = 0;
while($count < sizeof($array_id)){
foreach($array_id as $id){
$count_aux = 0;
foreach($content->xpath('//Event') as $header){
$result = ($header->xpath('Name')); // Should output 'something'.
if($result){
$titulo = (string) $result[0];
if($count == $count_aux){
$sql = "Update eventos_sapo set titulo='$titulo' where event_id='$id';";
mysqli_set_charset($con,"utf8");
if (mysqli_query($con, $sql)) {
echo $sql . "</br>";
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
$count_aux++;
}
$count++;
}
}
}
$array_id = insertEventId($con, $content);
insertTitulo($con, $content, $array_id);
Response of request:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://***/**/***" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://***.****.**/***/**" xmlns:ns3="http://**.**.**/**/**">
<SOAP-ENV:Body>
<ns1:GetAgendaV2Response>
<ns1:GetAgendaV2Result>
<ns1:Events>
<ns1:Event>
<ns1:Id>94343</ns1:Id>
<ns1:Name>Mexa-se Mais 2011 - Orientação no Jamor (BTT e Caminhada)</ns1:Name>
<ns1:Genre>
<ns1:Id>10</ns1:Id>
<ns1:Name>Outdoor</ns1:Name>
</ns1:Genre>
</ns1:Event>
<ns1:Event>
<ns1:Id>122611</ns1:Id>
<ns1:Name>«Memória da Politécnica: Quatro Séculos de Educação, Ciência e Cultura»</ns1:Name>
<ns1:Genre>
<ns1:Id>6</ns1:Id>
<ns1:Name>Exposições</ns1:Name>
</ns1:Genre>
</ns1:Event>
....

GCM send message to all devices [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem with GCM, I can't send a message to all devices.
This isn't the original code, but is my own version!
send_message.php:
<?php
if (isset($_POST["regId"]) && isset($_POST["message"])) {
//$regId = $_POST["regId"];
$message = $_POST["message"];
include './GCM.php';
$gcm = new GCM();
//$registatoin_ids = array($regId);
$message = array("price" => $message);
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if($users != false){
$no_of_users = mysql_num_rows($users);
}else{
$no_of_users = 0;
}
$i = 0;
while ($row = mysql_fetch_array($users)) {
$ids[$i] = $row["gcm_regid"];
$i++;
foreach ($ids as $value){
echo $value;
$registatoin_ids = $value;
json_encode($registatoin_ids);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
}
echo $value;
echo $registatoin_ids;
}
?>
GCM.php:
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.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_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;
}
}
?>
db_functions.php:
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once './db_connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $gcm_regid) {
// insert user into database
$result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
// check for successful store
if ($result) {
// get user details
$id = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
// return user details
if (mysql_num_rows($result) > 0) {
return mysql_fetch_array($result);
} else {
return false;
}
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmail($email) {
$result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");
return $result;
}
/**
* Getting all users
*/
public function getAllUsers() {
$result = mysql_query("select * FROM gcm_users");
return $result;
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
}
?>
The original code is from Ravi Tamada.
change send_message.php to the bellow code :
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
include_once 'db_functions.php';
if (isset($_GET["message"]) && isset($_GET["Number"])) {
$message = $_GET["message"];
$db = new DB_Functions();
$users = $db->getAllUsers();
$regIds = array();
while($row = mysql_fetch_array($users)) {
array_push($regIds,$row['gcm_regid']);
}
echo isset($users);
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
include_once './GCM.php';
$gcm = new GCM();
$message = array("message" => $message);
$result = $gcm->send_notification($regIds, $message);
echo $result;
}
?>

Categories