Having trouble parsing Json with PHP - php

I have an android app that sends a json string to my server and it is formatted as follows:
{"drink_name":"testing","phone_number":"5555555555"}
When I use the command: SELECT * FROM orders, it shows that blank entries were inserted into the table.
I think my issue is arising from my PHP script (mainly because I am new to PHP).
Am I parsing the json correctly?
Below is the script that I wrote.
<?php
$handle = mysql_connect('localhost',USERNAME,PASSWORD);
if($handle==false)
{
die('No database connection');
}
$db=mysql_select_db('r2bar2');
$json = file_get_contents('php://input');
$obj = json_decode($json);
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
mysql_close($handle);
?>
EDIT:
Here is my Android code if it is any help.
protected void sendJson(final String phnNmbr, final String drink) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost("http://kubie.dyndns-home.com/R2Bar2/sendOrder.php");
json.put("phone_number", phnNmbr);
json.put("drink_name", drink);
StringEntity se = new StringEntity( "orders: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}

I had used the same method except for how you are trying to access json data on the server.
I had used $_POST array to access it and it worked well for me. Try using,
$json = $_POST['orders'];
$obj = json_decode($json);
This had worked perfectly well for me. All the best :)
(I dont think there is a problem with $handle since something is being inserted into the table)

I figured out what I was doing wrong. It seems as though I was passing in a raw data type. In order to parse the string, I used the following:
$obj = json_decode(file_get_contents("php://input"));
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
Thanks everyone for your suggestions.

You have make a connection to the DB as follws,you have missed the $handle to make connection
$handle = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$handle) {
die('Not connected : ' . mysql_error());
}
// make r2bar2 the current db
$db=mysql_select_db('r2bar2',$handle);
if (!$db) {
die ('Can\'t use r2bar2 : ' . mysql_error());
}

Related

Getting a single field from HTTP Response

I am trying to get a single field from MySQL through php and use it in my android app.. how can i get a single field when reading response from php to android without using json?
or if there is any tutorial that can help me , I'll be grateful
here's my Code
public Boolean postData(String a,String b) {
response = null;
String response = null;
try
{
// url = new URL("http://"+"URL"+"/new/check2.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("check",x));
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
response = CustomHttpClient.executeHttpPost("http://"+"URL"+"/new/checkedited.php",postParameters);
// result = response.toString();
result = result.replaceAll("\\s+", "");
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
PHP
<?php
$host=""; // Host name
$user=""; // Mysql username
$pswd=""; // Mysql password
$db="pet_home"; // Database name
//$tbl_name="users"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
$username=$_POST['username'];
$password=$_POST['password'];
$result=mysql_query("select * from users where username='$username' and
password='$password'")or die (mysql_error());
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if ($count > 0){
echo "\n";
echo $row['filter_st'];
echo "\n";
echo $row['heat_st'];
echo "\n";
echo $row['led_st'];
}else{
echo 0;
}
?>
Just echo the single field then, no parsers, no JSON no nothing...
for example if you want 'heat_st': (just one echo, since the echo is the response you phone gets)
echo $row['heat_st'];
Then the response to your android app will be just that one String which is the result you wanted.( you can easily convert it to int for example in Java if you need to )
if you need multiple fields, JSON is the way to go.

Error in my php code when i call it from android device with httpPost

i am written a program for android devices that sends call logs to my database in my host. i use httpPost method to do this and other side i have a php code.
when i try to run this code in request i get a page in this mainly i see this :
500 Internal Server Error
and in Apache Error Log i give this error :
PHP Startup: Suhosin Extension does not officially support PHP 5.2 and below anymore, because it is discontinued. Use it at your own risk. in Unknown on line 0
my host provider don't permission me to directly change php.ini file.
some of my php code side :
function callLogSyncToCount()
{
global $serverAddress, $DBusername, $DBpassword, $DBname;
$userID = $_POST['userID'];
$data = $_POST['data'];
$logs = explode('`second`', $data);
foreach($logs as $item)
{
//list($number, $duration, $date, $type) = explode("`first`", $item);
$counter = 0;
$con = mysql_connect($serverAddress, $DBusername, $DBpassword) or die (mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
return false;
}
mysql_select_db($DBname, $con);mysql_query("SET NAMES 'utf8'");
$result = mysql_query("SELECT * FROM `call_log` WHERE `user_id` = '".$userID."' AND `number` = '".$number."' AND `date` = '".$date."' AND `type` = '".$type."'") or die (mysql_error());
while($row = mysql_fetch_array($result))
{
$counter++;
}
if ($counter < 1)
{
mysql_query("INSERT INTO `call_log`(`user_id`, `date`, `duration`, `number`, `type`) VALUES ('".$userID."', '".$date."', '".$duration."', '".$number."', '".$type."')") or die (mysql_error());
}
mysql_close($con) or die (mysql_error());
}
return true;
}
some of my androide side code is :
private class SyncToCount extends AsyncTask<String, Void, String> {
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... param) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(param[0]);
SimpleDateFormat mySQLFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mySQLFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
long ID = Long.parseLong(param[1]);
List<callLogType> calls = new ArrayList<CallLogUtility.callLogType>();
calls = getCallList();
String sendStr = "";
globalVars.syncLogSize = calls.size();
try {
int j = 0;
for(int i = 0; i < calls.size() && j < 20; i++)
{
if(calls.get(i).ID <= ID)
continue;
j++;
sendStr += calls.get(i).PhoneNumber + "`first`";
sendStr +=Integer.toString(calls.get(i).Duration)+ "`first`";
Date newDate = new SimpleDateFormat("d MMM yyyy hh:mm:ss z").parse(calls.get(i).Date);
sendStr +=mySQLFormat.format((newDate))+ "`first`";
sendStr +=Integer.toString(calls.get(i).Type)+ "`second`";
globalVars.syncLogUntil+=1;
}
} catch (Exception e) {
}
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("syncType", "calllogtocount"));
nameValuePairs.add(new BasicNameValuePair("userID", param[1]));
nameValuePairs.add(new BasicNameValuePair("data", sendStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
#SuppressWarnings("unused")
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
}
catch(Exception ex)
{
}
return null;
}
}
this code don't work but my log in code works properly whit syntax like this and from this android code and that server and php and database.
help me i am ambiguous whit php and android ...
My instinct here is that you have not initialized the variables that you are using and this is upsetting things. I am not following where the named variables are coming from I am assuming that there is no Register_globals going on here (hope not). If you are it would explain why the system is checking an error over PHP version in use although I think that is just a side effect of the commented out line.
My further instinct is to worry about the unescaped data being placed into the SQL statement but that could be a distraction if mysql_real_escape_string() can be used then it should to protect against (deliberate) bad user data as it's not. I wonder if you sent malformed data (from say a form) if you could trigger the error (or cause other errors like SQL injection)?
Have you tested the PHP with a basic form that submits the data exactly as you expect it? That would allow you to debug output data to a file or screen to see what is happening but it looks from here that the PHP code needs those variables explicitly set with values from $_POST.
It looks to me like the variables need filling but as the list line has been commented out that is not happening which could leave you with uninitialized variables which may or may not be upsetting things.
Other than that if you block comment out the code inside the foreach does it return true? If yes then I might be right and the problem is inside there so bring it back bit by bit until the error throws. If not then it is outside and you have eliminated half your code from you inquiries.
I hope that gives you something to work with. All the best with finding the source of your woes.

error manipulating cursor result from mongodb while getting resuts to android client

I'm connecting to local web server from android client and getting results back from mongodb database.
<?php
$Earth_radius = 6378.137; //KM
$required_distance = 20; //KM
if(! isset($_POST['long']) || ! isset($_POST['lat']) )
{
echo 'NOT SET'; //exit();
}
$long = $_POST['lat'];
$lat = $_POST['long'];
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->matabatdb;
// access collection
$collection = $db->matabat;
$center=array($long,$lat);
$radius=$required_distance/$Earth_radius; //convert to radians
echo 'Im Ok here ';
$result = $collection->find(array("loc"=>array('$within'=>array('$centerSphere'=>array($center,$radius)))));
echo ' I can reach here';
var_dump($result->getNext());
echo 'I do not reach this line';
?>
Any manipulation to $result doesn't provide any feedback response to android client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseText = EntityUtils.toString(entity);
Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?",Pattern.DOTALL);
Matcher matcher=pattern.matcher(responseText);
if(matcher.find()) {
String userID = matcher.group(1).trim();
}
else
Log.i(TAG," POST RESPONSE "+ responseText);
}
else
Log.i(TAG," POST RESPONSE is NULL");
The strange thing is If I made an html file and posted data manually the code works in the browser but regarding to android, I do not receive any data back or more specifically any data after manipulating the cursor. any echo statements before that line is received in Android.
Any help ?
If the PHP script works from the browser. Then it's perhaps a data encoding problem.
Try using json_encode($result->getNext()) instead of var_dump($result->getNext()).

Connecting mysql database with Android app

I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!

Send data from android to mysql

I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.

Categories