Issue with API PHP reading JSON - php

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

Related

how fetch multiple rows from mysql using prepared statements

With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.please assist me on how i fetch all rows from database instead of one
PHP function :
.....
public function StudentsOfParent($mobile){
$stmt = $this->conn->prepare("SELECT
a.id,
a.name,
a.mobile,
c.id as sutdentId,
c.user_id,
c.full_name,
c.school,
c.level,
c.year,
c.id
from users a
join students c
on a.id = c.user_id where a.mobile= ?");
$stmt->bind_param("i", $mobile);
if ($stmt->execute()) {
while ($user = $stmt->get_result()->fetch_assoc())
{
$stmt->close();
// return user's results
return $user;
}
}
else {
return NULL;
}
}
.....
External php file to access above function : retrieve.php:
<?php
include './DbHandler.php';
$db = new DbHandler();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['mobile'])){
$mobile = $_POST['mobile'];
$user = $db->StudentsOfParent($mobile);
if ($user != false) {
// user found successfully
$response["error"] = FALSE;
$response["user"]["id"] = $user["id"];
$response["user"]["sutdentId"] = $user["sutdentId"];
$response["user"]["user_id"] = $user["user_id"];
$response["user"]["full_name"] = $user["full_name"];
$response["user"]["school"] = $user["school"];
$response["user"]["level"] = $user["level"];
$response["user"]["year"] = $user["year"];
// $response["user"]["photo"] = $user["photo"];
echo json_encode($response);
// $json = json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Sorry we could not find you !";
echo json_encode($response);
}
}
else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.
That's because you're returning $user in the first iteration of while loop itself, the loop won't even go on for the 2nd iteration. Plus, you're also closing the statement object $stmt->close(); in the first iteration itself. Instead your code block should be like this:
// your code
$stmt->execute();
$result = $stmt->get_result();
$usersArr = array();
while ($user = $result->fetch_assoc()){
$usersArr[] = $user;
}
return $usersArr;
Now the returned $usersArr array is a multidimensional array, which you need to appropriately loop through to get all users' details. If you want to see the complete array structure, do var_dump($usersArr);.

JSON fields returning null when containing html tags

I am trying to expose some data in a table that contains HTML tags, when I access the page all of the fields not containing HTML are fine but any containing html return null.
I have tried setting the fields to VarChar and Text but neither seem to work. The table is also set to utf8_general_ci.
request_step_content.php
<?php
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");
$user = "userName";
$pass = "userPassword";
$table = "myTable";
$db=new PDO("mysql:host=localhost;dbname=$table", $user, $pass);
$query = "SELECT * FROM steps";
try {
$stmt = $db->query($query);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error.";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if($rows) {
$response["success"] = 1;
$response["message"] = "Step";
$response["step"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["intID"];
$post["heading"] = $row["strStepheading"];
$post["keyPrinciple"] = $row["strKeyPrinciple"];
$post["pillar"] = $row["strPillar"];
$post["introduction"] = $row["memIntroduction"];
$post["actionSteps"] = $row["memActionSteps"];
$post["actionPoints"] = $row["memActionPoints"];
$post["studyAndUnderstanding"] = $row["memStudyUnderstanding"];
array_push($response["step"], $post);
}
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "No Steps Available";
die(json_encode($response));
}
?>
json response
{"success":1,
"message":
"Step",
"step":[{"id":"1",
"heading":"Test Heading",
"keyPrinciple":"Key Principle: Test Key Principle",
"pillar":"Pillar 1: Pillar",
"introduction":null,
"actionSteps":null,
"actionPoints":null,
"studyAndUnderstanding":null}]}
The problem will be in encoding. Columns in DB tables can be UTF-8 but stored data doesnt have to be in UTF-8. PHP function json_encode accepts only UTF-8 data. Check your stored DB data.
I fixed the issue with some help of #Fky's answer regarding encoding.
Using utf_encode() I now have all fields including the html content in my JSON fields. Here's the edited code:
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["intID"];
$post["heading"] = $row["strStepheading"];
$post["keyPrinciple"] = $row["strKeyPrinciple"];
$post["pillar"] = $row["strPillar"];
$post["introduction"] = utf8_encode($row["memIntroduction"]);
$post["actionSteps"] = utf8_encode($row["memActionSteps"]);
$post["actionPoints"] = utf8_encode($row["memActionPoints"]);
$post["studyAndUnderstanding"] = utf8_encode($row["memStudyUnderstanding"]);
Thank you for the help all.

Issues with JSON in 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!

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"];

Query a base64 image from sql and decode it

I am trying to pull pictures from a table row that are base64 encoded. I need to decode them and display on a webpage. I would really like to put them into a slideshow but that is another topic!
Here is the query so far
<?php
require("config.inc.php");
//initial query
// table name is pictures and table row is picture
$query = "Select * FROM pictures";
//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"] = "Photos Available!";
$response["posts"] = array();
// only 3 rows in table - post_id, username, picture
foreach ($rows as $row) {
$post = array();
$post["post_id"] = $row["post_id"];
$post["username"] = $row["username"];
$post["picture"] = $row["picture"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Photos Available!";
die(json_encode($response));
}
?>
The problem is decoding it. Here is what it shows so far
http://www.photosfromfriends.com/webservice/gallery.php
This is only for one picture (post) The table might have 50 pictures in it and each will need to be displayed (hence the desire for a slideshow). This is way over my head and I would really appreciate any help.
try this code, please justify according to your code:
$data = json_decode($json, true);
//print_r($data);
$picture = base64_decode($data['posts'][0]['picture']);
header("Content-type: image/png");
echo $picture;
You must decode only decoded data for the image, and don't forget to use header

Categories