Cannot fetch the value from JsonArray - php

I am having problem fetching out the value from PHP coding to my android. The logcat shows that
:W/System.err: org.json.JSONException:
No value for posts.
This is my php code:
<?php
require("config1.php");
$query="SELECT commentName,comment FROM discussion_comment WHERE discussID = :discussID";
$query_params=array(':discussID'=> $_POST['discussID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows){
$response["success"]=1;
$response["message"]="Post Available";
$response["posts"]= array();
foreach ($rows as $row){
$post = array();
$post["commentName"] = $row["commentName"];
$post["comment"] = $row["comment"];
array_push($response["posts"], $post);
}
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No post Available!";
die(json_encode($response));
?>
When is remove the 'WHERE discussID = :discussID"', I am able to fetch the data, but some is not necessary. What other way to write with Where condition.
My java:
private static final String COMMENT_NAME="commentName";
private static final String COMMENT="comment";
private static final String COMMENT_VIEW_URL="http://fysystem.com/show_comment.php";
#Override
protected String doInBackground(String... args) {
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
Appreciate your help.

PHP
<?php
require("config1.php");
// Default message
$response = array('success'=>0, 'message'=>'Error. Pass required parameters');
// Check discussID exists in POST params
if(isset($_POST['discussID']) && $_POST['discussID']!=""){
$sql = 'SELECT `commentName`, `comment` FROM `discussion_comment` WHERE `discussID` = :discussID';
try {
// Hope $db is defined in config1.php
$stmt = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute(array(':discussID'=> $_POST['discussID']));
$response = array("success"=>0, "message"=>"Discussion Not found");
// If data exists
if($stmt->rowCount()>0){
// Fetching rows with a scrollable cursor
// http://php.net/manual/en/pdostatement.fetch.php
$posts = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$posts[] = array('commentName'=>$row['commentName'], 'comment' => $row['comment']);
}
// Set the success status 1 and add the posts in return response
$response = array('success'=>1, 'message'=>'Discussion found', 'posts'=>$posts);
}
$stmt = null;
}
catch (PDOException $e) {
// print $e->getMessage();
$response = array('success'=>0, 'message'=>'DB Error');
}
}
// Finally return the response
echo json_encode($response);
?>
Andorid
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
int success = json.getInt('success');
// Check before access posts data
if(success==1){
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
}else{
// Handle it here if parameters not exist or db error or no discussion found
}
}
Hope this helps!

Related

Cannot insert image into SQL Server database from android using PHP

Its been a lot of days i am trying to insert the biometric fingerprint scanned data into MS SQL Server database using android through PHP.
I am sharing my entire code this time , i have to complete it anyhow.
Please friends help me out solving this.
Android Code For Calling the Api:
public void registerFinger(Bitmap scannedImage) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
scannedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] fingerByte = byteArrayOutputStream.toByteArray();
String encodedFingerData = Base64.encodeToString(fingerByte, Base64.DEFAULT);
try {
h = new JSONObject();
h.put("FingerPrint", encodedFingerData);
} catch (Exception e) {
e.printStackTrace();
}
Call<UniversalPojo> call = apiInterfaces.registerFingerPrint(String.valueOf(empId), getRequestBody(h.toString()));
call.enqueue(new Callback<UniversalPojo>() {
#Override
public void onResponse(Call<UniversalPojo> call, Response<UniversalPojo> response) {
if (response.isSuccessful()) {
if (response.body().getStatus().equalsIgnoreCase("true")) {
showDialog("Registration Done.");
} else {
showDialog("Registration Failed.");
}
} else {
showDialog("Registration Failed.");
}
}
#Override
public void onFailure(Call<UniversalPojo> call, Throwable t) {
t.printStackTrace();
showDialog("Registration Failed.");
}
});
}
public RequestBody getRequestBody(String rawString) {
return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), rawString.toString());
}
RegisterFingerData.php
<?php
require_once 'db_functions.php';
$db = new db_functions();
$data = json_decode(file_get_contents('php://input'), true);
$FingerPrint = $data['FingerPrint'];
//decoding and converting the image into byte array
$a = base64_decode($FingerData);
$b = array();
foreach (str_split($a) as $c) {
$b[] = sprintf("%08b", ord($c));
}
$ifAlreadyExists = $db->registerFinger( $b );
?>
The column FingerData in EMPFINGERMASTER is of the varbinary(MAX) datatype.
registerFinger function
public function registerFinger($fingerPrint)
{
try {
$sqlString = "INSERT INTO EMPFINGERMASTER( FingerData ) values (?)";
$stmt = $this->conn->prepare($sqlString);
$params = array($fingerPrint);
$stmt->execute($params);
$row = $stmt->fetch();
if (!$stmt) {
$arr = $stmt->errorInfo();
print_r($arr);
}
if ($rows) {
echo true;
} else {
echo false;
}
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}
}
GetFingerPrintData() function
public function GetFingerPrintData($myId){
$sqlString = "SELECT FingerData from EMPFINGERMASTER WHERE MyId = 1";
$stmt = $this->conn->prepare($sqlString);
$params = array($myId);
$stmt->execute($params);
$row = $stmt->fetch();
if (!$stmt) {
$arr = $stmt->errorInfo();
print_r($arr);
}
if ($row) {
//reconverting the byte[] array to BASE64 String
$rawResult = $row['FingerData'];
$resim = substr($rawResult, 2);
$bin = hex2bin($rawResult);
$base64_image = base64_encode($bin);
echo $base64_image;
}
}
The data getting stored in the Database is exactly like this :
[B#623a5f2
but if i check in echo , it shows a big data before before converting it into byte[] in RegisterFingerData.php
And i am not be able to get the proper data at the time of retrieving.
My Question is , I want to store the data into DB and retrieve it for checking.
There are a lot of suggestions on other similar questions but after using them i have reached this final code , and still not be able to get the results.

Insert data into server

I have problem inserting data into my database. The data can't be inserted and it does not show any errors in my Logcat. I have working on it but still can't solve the problems. This is my PHP code:
<?php
require ("config1.php");
if(!empty($_POST)){
$query = "SELECT * FROM announcement WHERE announceID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
try{
$stmt=$db->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time) ";
$query_params= array(
':title'=>$_POST['title'];
':description'=>$_POST['description'];
':startDate' => $_POST['start_date'];
':endDate' => $_POST['end_date'];
':time' => $_POST['time'];
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response)
}
}
?>
Below is my java code:
protected String doInBackground(Void... params) {
RequestHandler rh=new RequestHandler();
HashMap<String,String> param= new HashMap<String, String>();
param.put(KEY_TITLE,announcement_title);
param.put(KEY_DESCRIPTION,announcement_desc);
param.put(KEY_START_DATE,start_date);
param.put(KEY_END_DATE,end_date);
param.put(KEY_TIME,time);
param.put(KEY_IMAGE,announcement_image);
String result= rh.sendPostRequest(ANNOUNCEMENT_URL,param);
return result;
}
Appreciate is someone can point out the problems.
You PHP Code Has Syntax error and Mysql preparement Placeholder error.
I Have Rewritten the Code kindly replace with your Old Code.
<?php
require ("config1.php");
if(!empty($_POST)){
//kindly filter the POST value
$query = "SELECT * FROM announcement WHERE announcementID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
$stmt=$db->prepare($query);
$stmt->execute($query_params);
/*
}catch(PDOException $e){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
*/
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time)";
//re written by Ajmal PraveeN
$query_params= array(
':title'=>$_POST['title'],
':description'=>$_POST['description'],
':startDate' => $_POST['start_date'],
':endDate' => $_POST['end_date'],
':time' => $_POST['time']
);
/*
try {
*/
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
/*
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
*/
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response);
}
}
?>
If your $_POST['announcementID'] is a numeric number i can re edit the post with a Sanitize and Title post too.

Error in php code.Maybe my for loop is wrong?

ok i am not familiar with php but i have to use it for my android application to take data from mysql server.This is what i ve done so far.When i call this script from the app i want to create a new booking row and all the booked seat rows that the user selected . The above php throws an exception but i dont know where.
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
$query_params1 = array(
':seatNo' => $_POST['seatNo']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat{$i}"]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
echo json_encode($response);
}
?>
and this is the java code where i call the php
protected String doInBackground(String... strings) {
String msg=null;
try {
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("showId", showId));
params.add(new BasicNameValuePair("size",Integer.toString(selectedSeats.size())));
for(int i=0; i<selectedSeats.size(); i++) {
params.add(new BasicNameValuePair("seat"+Integer.toString(i),Integer.to String(selectedSeats.get(i))));
}
JSONObject jsonObject=jsonParser.makeHttpRequest( LOGIN_URL, "POST", params);
msg = jsonObject.getString(TAG_MESSAGE);
}
catch (JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return msg;
}
I know that the tag seat* that i use may be a little bit unusual but i couldnt think anything else.
The weird think is that the above code works.It makes the changes in the database but the msg
"Reservation Completed! is never reachable because it throws an exception somewhere!
Try using the following to echo the json:
header('Content-Type: application/json');
echo json_encode($response);
Also, ommit the PHP closing tag ?>. Last but not least; make sure nothing else is being sent to output before echo-ing your JSON.
Complete answer:
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat" . $i]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
header('Content-Type: application/json');
echo json_encode($response);
}

PHP MySQL Select script

I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;

How to get all the product categories from the mysql db via php and return json array

I have an android app.
I want to send a get request to the get_categories.php file.
In the get_categories.php file I want to
$query_categories = "SELECT category_name FROM categories";
and return all the categories found in that table into a json array.
How can I do that?
This is my incomplete code:
if (!empty($_GET)) {
$query_categories = "SELECT category_name FROM categories";
$success = false;
try{
$sth = $connection->prepare($query_categories);
//$sth->execute(array(':user_id' => $user_id));
//$user_items_count = $sth->rowCount(); - these are lines from other php file I've used
foreach($)//??
$success = true;
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = $ex;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = 2;
$response["message"] = "something went wrong";
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;
$response["message"] = "Another brick in the wall";
echo json_encode($response);
$connection = null;
}
Later on, in my Java code, how do I decode that?
Usually up until this point, in my other JSON transfers, I've received normal Json object with no arrays and read them this way:
setUserLastSeen(json.getString(TAG_USER_LAST_SEEN)); //for example.
But how do I decode an array?
For php side this how you can get the categories array and make json,for prepared statements this is how you can accomplish
$success = false;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$success = true;
}
catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Connection failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$query_categories = "SELECT category_name FROM categories";
try{
$sth = $sth->prepare($query_categories );
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Prepare failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
try{
$sth->execute();
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Execute failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */
/* Output of $query_categories
Array
(
[0] => cat1
[1] => cat2
[2] => cat3
[3] => cat4
)
*/
/* json encode $query_categories
["cat1","cat2","cat3","cat4"]
*/
/* check if categories exist or not*/
if(empty($categories)){
$response["success"] = 0;
$response["message"] = "No categories found";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
$response["data"]=$categories;
die(json_encode($response));
$connection = null;
/* output
{"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]}
*/
} else {
$response["success"] = 2;/* don't where you are setting success to 2*/
$response["message"] = "something went wrong";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;/* don't where you are setting success to 3*/
$response["message"] = "Another brick in the wall";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
I am not good at java but here is the reference How to parse a JSON and turn its values into an Array?
/* store json string in the_json */
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("data");
Note: make sure on java side you must check the success from json which
must be ==1 and the_json_array is not null
PHP Data Objects
you can use below code to ferch data using json and then decode that json array:
=================================================================================
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your webservice");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("Data",""+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
String fd_ono=null;
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
fd_ono=json_data.getString("your column name");
textView.settext(fd_ono.toString());
}
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "Record not found", Toast.LENGTH_LONG).show();
}

Categories