I have created an application where user can send notification to other devices with php as backend and fcm notification. On successfully sending the notification it store the details of notification and notification sender(user) on mysql database with table name 'notification' and 'sender_details'. However, new empty data are being stored in these two table everyday while the app is not even opened by anybody. Please Help
<?php
include('../conn.php');
$api_key="xxx";
$url="https://fcm.googleapis.com/fcm/send";
$fields=json_encode(array('to'=>$to,'notification'=>$data));
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($fields));
$headers = array();
$headers[] = 'Authorization: key ='.$api_key;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}
//fetching data
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$date3 = date('Y-m-d');
$sqlm = "SELECT dateonly FROM user_details WHERE token='".$_POST['token']."' AND dateonly='$date3'";
$result3 = mysqli_query($conn, $sqlm);
if (mysqli_num_rows($result3) > 0) {
echo "alreadysend";
}else{
$sql = "SELECT * FROM data WHERE group='".$_POST['group']."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$to=$row["token"];
//for sending email
$email=$row["email"];
$time2=date_default_timezone_set('Asia/Katmandu');
$date2 = date('Y-m-d h:i:s a', time());
$sql2 = "INSERT INTO user_details (name, phone, city)
VALUES ('".$_POST['name']."', '".$_POST['phone']."', '".$_POST['city']."')";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
//end of second sql queries
// 2. for body of message
$body = $_POST["name"].' needs ' at '.$_POST["city"].', '.$_POST["hospital"].' hospital. Contact on the following number: '.$_POST["phone"].' (Message from them: '.$_POST["message"].')';
// 3. for title
$title = New Notification';
$data=array(
'title'=> $title,
'body'=>$body,
'image' => $img,
'vibrate' => 1
);
$time=date_default_timezone_set('Asia/Katmandu');
$date = date('Y-m-d h:i:s a', time());
$dateonly = date('Y-m-d');
$sql3 = "INSERT INTO notifications (title, body, time, dateonly)
VALUES ('$title', '$body', '$date', '$dateonly')";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
//end of third sql queries
notify($to,$data);
}
} else {
echo "noresults";
}
}
mysqli_close($conn);
?>
All the post data are being received from the app
Related
I have a while loop that checks my database for notifications with a status of 1. It then sends a notification to OneSignal.com's API so the user will get the notification.
The problem is, I'm trying to run the script so that it processes all records with a status of 1 as it makes the while loop, but once I include the function for OneSignal the while loop stops after processing only one record.
I cant figure it out, I tried moving things around, and when I put the send message function outside the while loop, the php variables for the user ID don't get passed to it?
What should I do?
<?php
require('connection.inc.php');
$notification = mysqli_query($con, "SELECT *, t1.id AS NotifID FROM notification AS t1 LEFT JOIN user AS t2 ON t1.action_user_id = t2.id WHERE status = '1' ORDER BY time_updated DESC") or die(mysql_error());
//GET NOTIFCATION RECORD
while ($row = mysqli_fetch_assoc($notification)) {
$notificationID = $row['NotifID'];
$type = $row['notification_type'];
$action_user_id = $row['action_user_id'];
$action_user_name = $row['name'];
$action_user_profile = empty($row['profile_image']) ? '/instachurch/images/profile/profile.png' : '/instachurch/' . $row['profile_image'];
$time = $row['time_updated'];
$post_id = $row['post_id'];
$notify_user_id = $row['notify_user_id'];
// GET NOTIFY USER INFO
$GetUserName = mysqli_query($con, "SELECT * FROM user WHERE id = $notify_user_id ") or die(mysql_error());
while ($row = mysqli_fetch_assoc($GetUserName)) {
$username = $row['name'];
$userMob = $row['mob'];
$userHash = $row['hash'];
$OneSignalPushID = $row['id'];
if ($type == "post_liked")
$message = $action_user_name . " liked your post.";
else if ($type == "post_comment")
$message = $action_user_name . " commented on your post.";
else if ($type == "post_comment_reply")
$message = $action_user_name . " replied to your comment.";
else if ($type == "post_answer")
$message = $action_user_name . " answered to your question.";
else if ($type == "follow_user")
$message = $action_user_name . " started following you.";
else if ($type == "discussion_topic_comment")
$message = $action_user_name . " commented on your forum topic.";
else if ($type == "timeline_mention")
$message = $action_user_name . " mentioned you in a comment.";
else if ($type == "school_lesson_mention" || $type == "school_discussion_mention")
$message = $action_user_name . " mentioned you in a comment on discussion.";
if ($type == "post_comment" || $type == "post_liked" || $type == "post_comment_reply" || $type == "post_answer" || $type == "timeline_mention")
$link = "http://www.gypsychristiannetwork.com/instachurch/post.php?post_id=" . $post_id . '&hash=' . $userHash;
else if ($type == "follow_user")
$link = "http://www.gypsychristiannetwork.com/instachurch/users.php?id=" . $action_user_id . '&hash=' . $userHash;
else if ($type == "discussion_topic_comment")
$link = "http://www.gypsychristiannetwork.com/tgcm/school/account.php?q=24&topic=" . $post_id . '&hash=' . $userHash;
else if ($type == "school_lesson_mention")
$link = "http://www.gypsychristiannetwork.com/tgcm/school/account.php?q=11&qid=" . $post_id . '&hash=' . $userHash;
else if ($type == "school_discussion_mention")
$link = "http://www.gypsychristiannetwork.com/tgcm/school/account.php?q=24&topic=" . $post_id . '&hash=' . $userHash;
}
$q3 = mysqli_query($con, "UPDATE `notification` SET `status` = '2' WHERE `id` = '$notificationID'");
echo $notificationID . ':' . $message;
// echo $link;
$userPushID = $OneSignalPushID;
// echo $userPushID.'<BR><P>';
$heading = 'Check your Notifications';
$content = array(
"en" => $message
);
$heading = array(
"en" => $heading
);
$fields = array(
'app_id' => "APPID",
'include_external_user_ids' => array(
"$userPushID"
),
'channel_for_external_user_ids' => 'push',
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'headings' => $heading,
'url' => $link
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic APPSECRET'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode($return);
print("\n\nJSON received:\n");
print($return);
print("\n");
}
?>
There seems to be a 'return $response' line near the bottom, which would probably break the while{}. Try removing that, or maybe rewrite that part
Well, if it were me, I would try to rework this first so there are fewer nested while loops. In this case, you can do it fairly simply, by iterating through the results (as you're doing) and pushing them to an array outside the function, like so:
$ary = array();
while($row = mysqli_fetch_array($yourQueryResults, MYSQLI_ASSOC))
{
array_push($ary, array($row['valueYouIntendToUseLater']));
}
Then you can run the interior while on the resulting array, like
foreach($element in $ary){
while.....etc
}
And so on. You get the drill. While this format is certainly not necessary, it does make debugging easier in my experience. As #Jelmer pointed out, the reason this while function is biting the dust is because you're calling return in it, which breaks the loop, as is its purpose.
Hi I am currently building a website where people can check the price of cyrptocurrencies. The coins I want to watch are in arrays, so it will read one by one and put it in the URL.
What I am now trying to do is to get all coins I want from the database and put it one by one in the URL. I already tried something by myself, but it is not working very well, and I am constantly getting errors or not the right result.
$array is the manual variable, and the ones above are the coins from the database
This is my code:
require_once('config.php');
$query = "SELECT * FROM targets";
$result = mysqli_query($mysqli, $query);
$datas = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$datas[] = $row;
}
}
foreach ($datas as $data) {
$test = "'".$data['coin']."', ";
}
$array = array('vertcoin', 'spectrecoin', 'carvertical');
foreach ($array as $coins) {
$url = "https://api.coinmarketcap.com/v1/ticker/".$coins."/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$parsed_json = json_decode($data);
$name = $parsed_json['0']->name;
$symbol = $parsed_json['0']->symbol;
$price_usd = $parsed_json['0']->price_usd;
$price_btc = $parsed_json['0']->price_btc;
$percent_change_1h = $parsed_json['0']->percent_change_1h;
$percent_change_24h = $parsed_json['0']->percent_change_24h;
$percent_change_7d = $parsed_json['0']->percent_change_7d;
echo "<br><br>name: ". $name ."<br>";
echo "symbol: ". $symbol ."<br>";
echo "price_usd: ". $price_usd ."<br>";
echo "price_btc: ". $price_btc ."<br>";
echo "1h change: ". $percent_change_1h ."<br>";
echo "24h change: ". $percent_change_24h ."<br>";
echo "7d change: ". $percent_change_7d ."<br><br>";
}
Seems like you are overwritting the $test value each time.
I do not understant which variable is what, but If I am not wrong the following statement is where you try to concatenate your values:
foreach ($datas as $data) {
if($test){
//when $test is not null remember the value.
$test = $test."'".$data['coin']."', ";
}else{
//Otherwise set $test
$test = "'".$data['coin']."', ";
}
}
Assuming the following table:
CREATE TABLE `targets` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`coin` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
With this data:
INSERT INTO `targets` (`id`, `coin`) VALUES
(1, 'vertcoin'),
(2, 'spectrecoin'),
(3, 'carvertical');
This code:
require_once 'config.php';
$query = "SELECT * FROM targets";
$result = mysqli_query($mysqli, $query);
$coinList = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$coinList[] = $row['coin'];
}
}
//print_r($datas);
foreach ($coinList as $coinItem) {
$url = "https://api.coinmarketcap.com/v1/ticker/".$coinItem."/";
echo sprintf('URL for coin '%s' is %s', $coinItem, $url);
// Rest of code goes here.
// curl etc.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$parsed_json = json_decode($data);
$name = $parsed_json['0']->name;
$symbol = $parsed_json['0']->symbol;
$price_usd = $parsed_json['0']->price_usd;
$price_btc = $parsed_json['0']->price_btc;
$percent_change_1h = $parsed_json['0']->percent_change_1h;
$percent_change_24h = $parsed_json['0']->percent_change_24h;
$percent_change_7d = $parsed_json['0']->percent_change_7d;
echo "<br><br>name: ". $name ."<br>";
echo "symbol: ". $symbol ."<br>";
echo "price_usd: ". $price_usd ."<br>";
echo "price_btc: ". $price_btc ."<br>";
echo "1h change: ". $percent_change_1h ."<br>";
echo "24h change: ". $percent_change_24h ."<br>";
echo "7d change: ". $percent_change_7d ."<br><br>";
}
Produces this output:
URL for coin vertcoin is https://api.coinmarketcap.com/v1/ticker/vertcoin/
name: Vertcoin
symbol: VTC
price_usd: 4.53398
price_btc: 0.00040362
1h change: -0.11
24h change: -2.77
7d change: 6.88
URL for coin spectrecoin is https://api.coinmarketcap.com/v1/ticker/spectrecoin/
name: Spectrecoin
symbol: XSPEC
price_usd: 2.93546
price_btc: 0.00026103
1h change: 0.01
24h change: -3.42
7d change: 14.64
URL for coin carvertical is https://api.coinmarketcap.com/v1/ticker/carvertical/
name: carVertical
symbol: CV
price_usd: 0.011548
price_btc: 0.00000103
1h change: 3.75
24h change: -8.44
7d change:
I have a database table which previously had a coloumn data having a json data in it
| data | - `"{"display":{"pageName":"TEBT Home","Name":"rtryrtyrty rtyrtyrtyrty",
"Email":"trupti.gjklhjkgv#gmail.com","state":"WB","city":"CTY_ARAM",
"dob":"09/12/1964"}}"`
now I want to restructure my data_table and add different coloumns for pageName , Name, Email, state, city, dob and want to exlpode the json data already present in 'data' coloumn.
this is the logic I am trying to Implement , but it doesn't work .
<?php
$dataString = "SELECT data FROM data_table";
$result = mysqli_query($conn, $dataString);
$data =array();
while($row=mysqli_fetch_assoc($result)){
$data[] = $row['data'];
}
$iterations = ceil(count($data));
for ($x = 0; $x <$iterations; $x++) {
echo "The number is: ".$x." <br>";
if (!empty($data)) {
$json = json_decode($data, true);
$page = $json['display']['pageName'];
$name = $json['display']['Name'];
$email =$json['display']['Email'];
$mob =$json['display']['mobno'];
$state =$json['display']['state'];
$city =$json['display']['city'];
$dob =$json['display']['dob'];
echo $page;
$sql = "UPDATE data_table SET page = '".$page."' WHERE data ='".$data."' ";
mysqli_query($conn, $sql);
}
else
{
echo "done";
}
}
?>
use this code to see db error if any :
$dataString = "SELECT data FROM data_table";
$result = mysqli_query($conn, $dataString);
$data =array();
while($row=mysqli_fetch_assoc($result)){
$data[] = $row['data'];
}
$iterations = ceil(count($data));
for ($x = 0; $x <$iterations; $x++) {
echo "The number is: ".$x." <br>";
if (!empty($data)) {
$json = json_decode($data, true);
$page = $json['display']['pageName'];
$name = $json['display']['Name'];
$email =$json['display']['Email'];
$mob =$json['display']['mobno'];
$state =$json['display']['state'];
$city =$json['display']['city'];
$dob =$json['display']['dob'];
echo $page;
$sql = "UPDATE data_table SET page = '".$page."' WHERE data ='".$data."' ";
mysqli_query($conn, $sql);
echo("Error description: " . mysqli_error($con)); // added to see error msg
}
I am trying to send sms to all the members in a mysql table using API.
I am able to send the sms.
But only first row in the table is being used, whereas I want that the sms is sent to all the records in the table.
The code I am using is like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$result = mysql_query("SELECT name,mobile FROM members");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$mobile=$row[1];
$name=$row[0];
$request = "";
$param['mobileno'] = "91". $mobile;
$param['message'] = "Dear $name (organisation name) wishes you a very very Happy Birthday";
$param['username'] = "username";
$param['password'] = "password";
$param['sendername'] = "sender";
foreach ($param as $key => $val ){$request .= $key . "=" . urlencode($val);
$request .= "&";}$request = substr( $request, 0, strlen( $request ) - 1 );
$url = "http://smsapi" . $request;
$ch = curl_init($url);curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
var_dump($result);exit;
curl_close( $ch );
I have modified the code as per the suggestions in the answers, but I am still getting the result for the first row only.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$result = mysql_query("SELECT name,mobile FROM members");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result)) {
$mobile=$row[1];
$name=$row[0];
$request = "";
$param['mobileno'] = "91". $mobile;
$param['message'] = "Dear $name (organisation name) wishes you a very very Happy Birthday";
$param['username'] = "username";
$param['password'] = "password";
$param['sendername'] = "sender";
foreach ($param as $key => $val ){$request .= $key . "=" . urlencode($val);
$request .= "&";}$request = substr( $request, 0, strlen( $request ) - 1 );
$url = "http://smsapi" . $request;
$ch = curl_init($url);curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
var_dump($result);exit;
curl_close( $ch );
}
Use while($row = mysql_fetch_row($result)) to loop through the rows.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$result = mysql_query("SELECT name,mobile FROM members");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result)) {
$mobile=$row[1];
$name=$row[0];
$request = "";
$param['mobileno'] = "91". $mobile;
$param['message'] = "Dear $name (organisation name) wishes you a very very Happy Birthday";
$param['username'] = "username";
$param['password'] = "password";
$param['sendername'] = "sender";
foreach ($param as $key => $val ){$request .= $key . "=" . urlencode($val);
$request .= "&";}$request = substr( $request, 0, strlen( $request ) - 1 );
$url = "http://smsapi" . $request;
$ch = curl_init($url);curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
var_dump($result);exit;
curl_close( $ch );
}
You need to loop all the rows.
something like:
while($row = mysql_fetch_row($result)) { .... }
also, the php mysql extension is deprecated, have a look at mysqli or pdo.
You're using mysql_fetch_row, which to my understanding only returns one row (if any is found). Consider using mysql_fetch_all instead
I have a PHP script with which I want to read servers from database and connect to them with cURL. Servers responds with results from sql query. The problem is that script after each respond from server displays number 1. The ouput looks like this:
Server 1: some results
1Server 2: some results
1Server 3: some results
1
Here is the code that reads servers from database and connects to them:
<?php
$mysql_id = mysql_connect('localhost', 'ms', 'pass');
mysql_select_db('servers', $mysql_id);
mysql_query("SET NAMES utf8");
$query = "SELECT * FROM svr";
$result = mysql_query($query);
$num = mysql_num_rows($result);
while ($data = mysql_fetch_assoc($result))
{
$server[] = $data;
}
mysql_close($mysql_id);
$i = 0;
while($i < $num) {
$dealer = $server[$i]['dealer'];
echo $dealer . "<br />";
$data = "val=a"; //just for testing
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/html; charset=utf-8')
);
$result = curl_exec($ch);
echo $result;
$i++;
}
?>
I discovered that 1 is displayed with "echo $result;" and the code for creating response is this:
<?php
$mysql_id1 = mysql_connect('localhost', 'ms', 'pass');
mysql_select_db('servers', $mysql_id1);
mysql_query("SET NAMES utf8");
$query2 = "SELECT * FROM data";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows($result2);
while ($data2 = mysql_fetch_assoc($result2))
{
$deli[] = $data2;
}
$i1 = 0;
$space = " ";
while ($i1 < $num2) {
echo $space . $deli[$i1]['id'] . " ";
echo $deli[$i1]['artikel'] . " ";
echo $deli[$i1]['znamka'] . " ";
echo $deli[$i1]['model'] . " ";
echo $deli[$i1]['letnik'] . " ";
echo $deli[$i1]['cena'] . " € ";
echo $deli[$i1]['zaloga'] . "<br />";
$i1++;
}
echo "<br />";
mysql_close($mysql_id1);
?>
Please help me
Use the CURLOPT_RETURNTRANSFER option. Otherwise cURL will automatically echo the data and just return true (which is converted to 1 by echo).
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
PHP.net says,
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.
You need to use CURLOPT_RETURNTRANSFE or curl_exec returns a statuscode and sends the response to stdout:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
CURLOPT_RETURNTRANSFER shoud be TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.read the full documentation php.net
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
or you can do
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
Use CURLOPT_RETURNTRANSFE or else it will return a status-code and sends the response to stdout:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Man, if the user can change dealer field or $deli fields you have got stored XSS vulnerability here.
$dealer = $server[$i]['dealer'];
echo $dealer . "<br />";
echo $space . $deli[$i1]['id'] . " ";
...etc
use
htmlentities($your fields)
to solve this problem