Issues with JSON in PHP - php

I am trying to create a restAPI to get some details from MySQL for this I have created a PHP file to access them on Android devices.
Here is the PHP file:
<?php
include("db_details.php");
$response = array();
if (isset($_POST['userID']))
{
$userID = $_POST['userID'];
$grantedvalue = "granted";
$stmt = mysqli_prepare($bd, "SELECT p.name, p.userURL, a.grantaccuracy FROM loc_details d JOIN loc_profile p ON d.userID = p.userId JOIN loc_friends a on a.userId = d.userId WHERE a.grantstatus = ? and a.grantuserID = ?");
mysqli_stmt_bind_param($stmt, "ss", $grantedvalue, $userID);
$checkresult = mysqli_stmt_execute($stmt);
$result = $stmt->get_result();
if (!$checkresult)
{
die("Error updating user_details_table: " . mysqli_stmt_error($stmt));
}
else
{
echo $result -> num_rows;
if($result -> num_rows > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
// temp user array
$detail = array();
$detail["name"] = $row["name"];
$detail["userURL"] = $row["userURL"];
$detail["grantaccuracy"] = $row["grantaccuracy"];
array_push($response["details"], $detail);
}
$response["success"] = 1;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Zero Data";
echo json_encode($response);
}
}
}
else
{
$response["success"] = 300;
$response["message"] = "issue with getting values";
echo json_encode($response);
}
?>
I am using AsyncHttpClient Library to access the above php file. The results are not coming up there but when I try to access the php directly on browser something like this:
http://www.thiswillhavemycompanydomain.com/loc/get_user_details.php?userID=2238
The results are getting printed correctly on the browser. So I thought it could be an issue with coding part in android hence I tried using the Chrome Extension (Advance REST CLIENT) to see if I can get the results.. Strangely I am not getting results even there. I am always getting the else part of if (isset($_POST['userID'])) from the php code.
Not sure what could be wrong here as I can view all the data on my browser directly but not on ARC or my android APP?
Can somebody help me fix this as I don't know where could be the problem?
Thanks!

Related

Issue with API PHP reading JSON

There seems to be an issue with the API handling JSON input.
This is my API (Delete function)
function doDeleteCustomer() {
global $db;
if(isParamSet(array('id'))) {
if(isParamAvailable(array('id'))) {
$customerId = $_REQUEST['id'];
$sql = "DELETE FROM customers WHERE ID=:customerid";
$stmt = $db->prepare($sql);
$stmt->execute(
array(
':customerid' => $customerId
)
);
if($stmt->rowCount() > 0) {
$response = array();
$response["error"] = false;
$response["status"] = 200;
$response["data"] = array();
$response["message"] = "Successfully removed customer!";
} else {
$response = array();
$response["error"] = true;
$response["status"] = 400;
$response["data"] = array();
$response["message"] = "Unable to remove customer!";
}
return json_encode($response);
}
}
}
When I test it in Postman everything works fine, but I have provide the information in x-www-form-urlencoded.
But when I want to give the input by raw JSON data I get a message that the required id field is missing...What am I doing wrong?
You have to use json_decode before processing your data if you intend to make your application accept json. Alternatively, if you'd like it to support both, you could use try catch in order to switch.
More information about json_decode can be found here and here.
I have found it, thanks to the this from Zirc.
All I needed to do was $_REQUEST = json_decode(file_get_contents('php://input'), true);
before the first if statement

PHP JSON not displaying MySQL result

The PHP I created retrieve data from a MySQL database and turns it into a JSON which is then echoed. I had 300 records and the PHP was able to display the JSON and was visible when viewed.
However, I added another 100 records to the same table and for some reason the JSON isn't being displayed. It just appears blank with no error. But when I remove the 100 records, the JSON displays as normal.
I haven't touched the PHP file during this. What could the reason be?
<?PHP
include_once("connection.php");
$query = "select id,mosque_name,latitude,longitude from mosques;";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
$response["mosques"] = array();
while ($row = mysqli_fetch_array($result)) {
$mosque = array();
$mosque["id"] = $row["id"];
$mosque["mosque_name"] = $row["mosque_name"];
$mosque["latitude"] = $row["latitude"];
$mosque["longitude"] = $row["longitude"];
array_push($response["mosques"], $mosque);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No mosques found";
echo json_encode($response);
}
?>
Try This:-
<?PHP
include_once("connection.php");
$query = "select id,mosque_name,latitude,longitude from mosques;";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 0) {
echo json_encode("");
}
else{
while ($row = mysqli_fetch_array($result)) {
/*$mosque = array();
$mosque["id"] = $row["id"];
$mosque["mosque_name"] = $row["mosque_name"];
$mosque["latitude"] = $row["latitude"];
$mosque["longitude"] = $row["longitude"];*/
$fetchRow[]=$row;
// array_push($response["mosques"], $mosque);
}
echo json_encode($fetchRow);
}
/* $response["success"] = 1;
echoing JSON response
echo json_encode($response);*/
?>
and check your result from network

Run php action for every element

I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.

Delete query is not working in PHP

I am trying to delete a particular id from a table in PHP. I have written two queries in the same php.
something like this:
<?php
include("db.php");
$response = array();
if (isset($_POST['userID']))
{
$userID = $_POST['userID'];
$result1 = mysql_query("DELETE FROM profile WHERE userID = '$userID'");
$result2 = mysql_query("DELETE FROM profile_details WHERE userID = '$userID'");
if ($result1 && $result2 )
{
$response["success"] = 1;
$response["message"] = "row successfully created.";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
}
else
{
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
I get the following error:
Parse error: syntax error, unexpected '$result1' (T_VARIABLE) in /homepages/htdocs/radiansa.com/extras/a/test2.php on line 16
I am not sure what could be wrong here..
First of all... stop using mysql_ and switch to PDO or mysqli_. The old ext/mysql mysql_*() functions were deprecated in PHP 5.5 and will eventually be removed entirely.
This needs attention also. Too vulnerable to anything.
$userID = $_POST['userID'];
For your problem, now. Change:
$result = mysql_query("xxxxxxx");
to
$result = mysql_query("xxxxx") or die(mysql_error());
It will help you debug your problem and point you to the right direction

PHP doesnt display anything

Hi guys I'm new to PHP and I'm trying to display all info in my admin table. When I test my PHP file it gives me a blank page, here is my php code. There's no error but I get a blank page and nothing was returned when I execute it.
<?php
require('connect.inc.php');
require('admin.config.inc.php');
require('core.inc.php');
if (!empty($_POST)) {
//initial query
$query = "SELECT * FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["users"] = array();
foreach($rows as $row) {
$user = array();
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["users"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
Put this at the head of the script to see what response you get. Then others may be able to help you according to the error you get.
ini_set('display_errors',1);
error_reporting(E_ALL);
I see you have also began with:
if (!empty($_POST)) {
}
$_POST IS An associative array of variables passed to the current script via the HTTP POST method.
$_POST is defined where. this should be some thing like $_POST['user']
You begin with:
if (!empty($_POST)) {
which is empty by default, so you go directly to the else statement which is empty as well!
You are declaring $user = array(); inside the loop, It has to be outside of the loop
$user = array();
foreach($rows as $row) {
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];

Categories