php connection with android project - php

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.

Related

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...

calling json data to php at server side in android

Hi,
i use this class to make a request to server, which consist of the json data object.
Class is:-
public class HttpClient {
private static String URL = "localhost/json/json_handle.php";
public String postJsonData(String data) {
try {
StringBuffer buffer = new StringBuffer();
// Apache HTTP Reqeust
System.out.println("Sending data..");
System.out.println("Data: [" + data + "]");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> nvList = new ArrayList<NameValuePair>();
BasicNameValuePair bnvp = new BasicNameValuePair("json", data.toString());
// We can add more
nvList.add(bnvp);
post.setEntity(new UrlEncodedFormEntity(nvList));
HttpResponse resp = client.execute(post);
// We read the response
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
is.close();
buffer.append(str.toString());
// Done!
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
Then i use a php class on server side to get the json object from the request. But, at server side i am getting nothing. Even when i use $_REQUEST method, then code after this method doesn't work.
Here is my php file:-
<?php
$file = fopen("MyFile.txt" ,"w");
$int = $_REQUEST;
fwrite($file,"aaa");
//$input =$_REQUEST['json'];
fwrite($file,"HELLO 111");
//$data = json_decode($input,true);
/*print_r($input);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}*/
//fwrite($file, $data);
fclose($file);
?>
Any suggestions regarding this problem???
Thanks friends for your help.
I got the solution and now the program is working perfectly on localhost as well as online.
For localhost, we just have to give the URL as:-
1.1.1.1/json/json_handle.php
where 1.1.1.1 is your ip address.
Again, thanks alot friends.

Can i get a single field from php to android without using json?

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 from php to android without using json? im trying to set a radiobutton's text into the field i get? here's my php code:
<?php
$con = mysql_connect("localhost","root","pass123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("voting", $con);
$result = mysql_query("SELECT Name FROM ssc_president WHERE Party = '123'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$pname = $row['Name'];
//echo "Name: ".$row['Name'];
mysql_close($con);
?>
You can use XML to get single name from server other than that You will have to hard code text of radio button in android.
To get dynamic data from server you need to call webservice which give data either in XML or JSON. Its depend on which you are using.
From PHP, simply echo the field you want. Make sure that is all you print.
<?php
...
echo $mydata;
?>
And from Android, read it with an HttpClient
String result = "";
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MyURLGoesHERE");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
}catch(Exception ex){
Log.e("Error",ex.toString());
}
Log.d("DataFromPHP",result);

JSON receiving data from android

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;
?>

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