JSON receiving data from android - php

I am new to php. I am posting data to php server from android as--
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("name", "john");
String url = "http://10.0.2.2/WebService/submitname.php";
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("json", jsonObject.toString());
StringEntity se = null;
se = new StringEntity(jsonObject.toString());
se.setContentEncoding(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
int i = response.getStatusLine().getStatusCode();
Log.v("status", "" + i);
} catch (Exception e)
{
e.printStackTrace();
}
And receiving the data in php as
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$var',true);");
echo $var;
?>
Getting nothing on server side. However php query is executing correct as getting 200 response and a new row in database but with empty retrived_name and cat field.
How do I solve this? Thanks in advance!

You Should provide the values in Query:
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
$name = $_POST['name'];
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$name',true);");
echo $var;
?>

Related

php connection with android project

I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.

Post request receives null value

I am developing a software wherein I send a post request to server (which is written in PHP) but the server receives null value. Any help would be appreciated.
Android and PHP files enclosed.
**This is my Android file:**
public static JSONObject tosend = new JSONObject();
for(int i=0;i<3;i++)
{
JSONObject jo = new JSONObject();
jo.put("infoName", infoName[i]);
jo.put("infoNumber", infoNumber[i]);
jo.put("direction",direction[i]);
jo.put("version",version[i]);
JSONArray ja = new JSONArray();
ja.put(jo);
tosend .accumulate("introduceesJson", ja);
}
String link = "http://172.65.45.7/checkAppInstalled.php";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(link);
StringEntity se;
se = new StringEntity(tosend.toString());
// Set HTTP parameters
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "*/*");
httpPostRequest.setHeader("Content-type", "*/*");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
//long t = System.currentTimeMillis();
/* HttpPost httpPostRequest = new HttpPost(link);
List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);
nVP.add(new BasicNameValuePair("json", tosend.toString()));
httpPostRequest.setEntity(new UrlEncodedFormEntity(nVP));*/
//Log.e("Posted data", "TestPOST - nVP = "+nVP.toString());
// Hand the NVP to the POST
Log.e("posted data",tosend.toString());
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
String jsonReceived = EntityUtils.toString(entity);
Log.e("result received",jsonReceived);
}
Here's my PHP code:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
foreach($jsonObj as $json){
echo $json['infoName'];
echo $json['infoNumber'];
echo $json['direction'];
echo $json['version'];
}
}
else
{
echo "json empty";
}
Here is the logcat result:
04-02 15:34:07.882 9526-9704/com.thoughtrix.introduce E/posted data﹕ {"introduceesJson":[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"},[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"}]]}
Result Received : json empty.
Dont know much from json but fiddled around a bit: Try this:
var_dump($jsonObj['introduceesJson']);
$jsonArray = $jsonObj['introduceesJson'];
foreach($jsonArray as $json)
{
echo("------\n");
var_dump ($json);
foreach ( $json as $jsonarray )
{
echo(" ------\n");
var_dump ($jsonarray);
echo $jsonarray['infoName'];
echo $jsonarray['infoNumber'];
echo $jsonarray['direction'];
echo $jsonarray['version'];
echo ("\n");
}
} –
Could you please post the complete php script to extract all variables when you are done? I was puzzled...

Android Json to Server sends not data

I got a problem. I read a lot here but unfortunately I can't get an answer for my problem.
I want to send a Json post to my Server. The Server should then save the string in my database.
This is my server code so far:
<?php
include('db_connect.php');
$db = new _DB_Connect();
$db->connect();
if(isset($_POST['regid'])){
$data = json_decode($_POST['regid']);
$save_entry = "insert into gcm_users (gcm_regid) values ('$data')";
mysql_query($save_entry) or die (mysql_error());
}else{
echo 'no data get';
}
?>
And this is my method on my android phone.
public String sendJson(View view){
InputStream inputStream = null;
String result = "";
String url2 = "http://192.168.0.5/control_center/functions/incomming.php";
TextView textView_result;
textView_result = (TextView) findViewById(R.id.textView_result);
//strict mode for networking
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type" , "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null) {
System.out.println(convertInputStreamToString(inputStream));
}
else {
result = "Did not work!";
}
textView_result.setText(httpResponse.toString());
System.out.println(jsonObject.toString());
}catch(JSONException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Now the
System.out.println(convertInputStreamToString(inputStream));
tells me that I got no data
echo 'no data get';
So I get a response form the server but I could find my error, why the post data could not be retrieved.
Would appreciate any help or hints. Thank you.
try this...
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
MultipartEntityBuilder multiPart = MultipartEntityBuilder.create();
multiPart.addTextBody("regid",json);
or
multiPart.addTextBody("regid","blablabla");
httpPost.setEntity(multiPart.build());

How to extract json data and insert in mysql php

Actually I am new to android web services so please help me
my problem I am sending json encoded data from mobile client and I am getting json data on server side so that
client side code:
mJobject.put("userName", contactname.getText().toString());
mJobject.put("phonenumber",phonenumber.getText().toString() );
mJArray.put(mJobject);
Log.v(Tag, "^============send request" + mJArray.toString());
contactparams.add(new BasicNameValuePair("contactdetails", mJArray.toString()));
Log.v(Tag, "^============send request params" + mJArray.toString());
jsonString=WebAPIRequest.postJsonData("http://localhost/contactupload/contactindex.php",contactparams);
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
and php side I am doing
<?php
$json_data=$_POST['contactdetails'];
$data=json_decode($json_data);
print_r($data);
?>
I am getting response
Array
(
[0] => stdClass Object
(
[phone number] => 5555
[username] => xfg
)
)
so how can I extract json data in php and insert in mysql
Do somehting like this..
<?php
$json_data=$_POST['contactdetails'];
$data=json_decode($json_data, true); // Added true flag
// You can access your variables like this..
echo $data['phone number'];// prints "5555"
echo $data['username']; // prints "xfg"
//do your db connection...
// execute your query with those variables...
?>
here is a sample code
I assume you know how to parse json from android.
now in your server code use this to get the data from url and insert them to mysql
// check for required fields
if (isset($_POST['location']) && isset($_POST['email']) && isset($_POST['lat']) && isset($_POST['longitude'])) {
$location = $_POST['location'];
$email = $_POST['email'];
$lat = $_POST['lat'];
$longitude = $_POST['longitude'];
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);
// mysql inserting a new row
$result = mysql_query("INSERT INTO marked_locations(location, email,lat,longitude) VALUES('$location', '$email', '$lat','$longitude')");
.....
..
if you have any doughts or have need more help just comment

HttpPost not posting correctly

My HttpPost code posts to my Database. But it posts blank values into it. I am new to this whole part of Android, so I am sure its a really dumb mistake but hopefully someone can help me out.
Android Code:
String name = "test";
String _score = String.valueOf(score);
String _time = String.valueOf(seconds);
try {
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost(
"http://www.laytproducts.com/plantzsubmithighscore.php");
final List pair = new ArrayList(3);
pair.add(new BasicNameValuePair("name", name));
pair.add(new BasicNameValuePair("score", _score));
pair.add(new BasicNameValuePair("time", _time));
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
String result = sb.toString();
Log.i("Plantz","FillBucket Highscore result:\n"+result);
} catch (Exception e) {
Log.e("Plantz", "Error in http connection: "+e.toString());
}
Php:
<?php
$con = mysql_connect("localhost","MY_USER","MY_PASS");
$name = $_GET["name"];
$score = $_GET["score"];
$time = $_GET["time"];
if(!$con){
echo("COULDN'T CONNECT! " . mysql_error());
die("COULDN'T CONNECT! " . mysql_error());
}
mysql_select_db("laytprod_plantz",$con);
mysql_query("INSERT INTO bucket_highscore (Name, Score, Time) VALUES ('$name','$score','$time')");
mysql_close();
?>
In your Android code, you're sending the query as part of the message body via HTTP POST. In the PHP code, you're attempting to read the values from $_GET. PHP code should be using $_POST, or better yet, $_REQUEST, in order to read values obtained through HTTP POST.

Categories