How to get a variable from php to android? - php

I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.

You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}

Related

How to get a count value from server into json in android?

I am trying to retrieve the number of rows in my server table using json parsing and php in android.
I have done the following coding in php and I am getting the value also, but I don 't know how to proceed with the json. Please guide me step by step what to do or where I am going wrong. My codes and error logs are as follows:
php code:
<?php
mysql_connect("localhost","user","pswd");
mysql_select_db("demo");
$username= (isset($_POST['receivenumber'])) ? $_POST['receivenumber'] : '';
$q=mysql_query("SELECT COUNT(receivenumber) FROM `addtasknew` where `receivenumber` = '$username'") or die(mysql_error());
$row=mysql_fetch_assoc($q);
print (json_encode($row));
mysql_close();
?>
json codes in android
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mydomainname.org/task/getmytaskcount.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// String h="123";
//nameValuePairs.add(new BasicNameValuePair("to",h.toString()));
nameValuePairs.add(new BasicNameValuePair("receivenumber","9595959595"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success "+nameValuePairs);
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getActivity(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getActivity(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
try
{
// I don't know wht to do here to get the count value
JSONArray jArray = new JSONArray(result);
Log.w("Lengh",""+jArray);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getActivity(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
error logs:
E/log_tag(2386): result ?{"COUNT(receivenumber)":"2"}
E/log_tag(2386): Error parsing data org.json.JSONException: Value {"COUNT(receivenumber)":"2"} of type org.json.JSONObject cannot be converted to JSONArray
You are trying to interpret your JSON as a JSONArray but it's a JSONObject.
To retrieve your value try this:
JSONObject jObj = new JSONObject(result);
String count= jObj.getString("COUNT(receivenumber)");
You can check this tutorial to learn more about JSON in android.
Try this
try {
JSONObject jObj = new JSONObject(result);
Log.i("COUNT",jObj.getString("COUNT") + " COUNT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and change the sql query like
"SELECT COUNT(receivenumber) as COUNT FROM addtasknew where receivenumber = '$username'";

How to obtain a certain data from an external sql database?

I'd like to get data from an external database the fastest way. My problem is that I can make the query and get all the data then using JSON I am able to obtain what I need. But I am curious if there is a faster solution, so I go over all the data in the php, then find the appropriate data I need and returning ONLY it to the JSON instead of the whole query. The first solution might be slow when I need hunderds of records out of one million.
This would be the .php code looking for the username in case of an ID. How can I give that ID to the .php script?
$ID = $_GET['ID'];
try {
$stmt = $conn->prepare("SELECT USERNAME FROM APPUSERS WHERE ID=?");
$stmt -> execute(array($id));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$userdata[] = $row;
}
$response = '1';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response = '0';
}
print(json_encode($userdata));
If I remove the WHERE part of the sql code I can get all records in the table with the following code:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebpage.com/query.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
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();
Bresult=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
Then from this Bresult variable I get retrieve the appropriate record e.g.
JSONArray jArray = new JSONArray(ViewPagerActivity.Bresult);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
if (jsonObject.getString("ID").equals("12345") {
String user = jsonObject.getString("USERNAME");
}
}
So I go through all the records then retrieve the username I need.
However, I think this can be made faster if I can retrieve only the username I need and not all the records. The question is, how I can do it?
Thank you in advance!!

Json data from php server not working.

I am uplodaing data in MYSQL data base and at the same time I want to retrieve one of the attribute which I have inserted, for the satisfaction of my successful upload. when I press the button for first time then, it only upload the data to the server, and return nothing. Again when I hit the button then it does both the processs(insertion and retrieving data), so I can't return value at a first time in form of json object.
This is my php code engrdatainsert.php
<?php
$sqlCon=mysql_connect("localhost","root","");
mysql_select_db("PeopleData");
//Retrieve the data from the Android Post done by and Engr...
$adp_no = $_REQUEST['adp_no'];
$building_no = $_POST['building_no'];
$contractor_name = $_POST['contractor_name'];
$officer_name = $_POST['officer_name'];
$area = $_POST['area'];
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
//--------Now check out the transaction status of the Inserted data---------||
$q=mysql_query("SELECT adp_no FROM engrdata WHERE adp_no='$adp_no'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));//conveting into json array
mysql_close();
?>
My Android code
public void insertdata()
{
InputStream is=null;
String result=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("adp_no",adp));//"34"));
nameValuePairs.add(new BasicNameValuePair("building_no",bldng));//"72"));
nameValuePairs.add(new BasicNameValuePair("area",myarea));//"72"));
nameValuePairs.add(new BasicNameValuePair("contractor_name",cntrct));//"72"));
nameValuePairs.add(new BasicNameValuePair("officer_name",ofcr));//"72"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidconnection/engrdatainsert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert the input strem into a string value
try
{
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();
result=sb.toString();
}
catch(Exception e)
{ Log.e("log_tag", "Error converting result "+e.toString()); }
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Toast.makeText(this, "data is "+json_data.getString("adp_no")+"\n", Toast.LENGTH_LONG).show();
String return_val = json_data.getString("adp_no");
if(return_val!=null)
{
Intent offff=new Intent(this,MainActivity.class);
offff.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
offff.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(offff);
}
}
}
//}
catch(JSONException e)
{ Log.e("log_tag", "Error parsing data "+e.toString()); }
// return returnString;//*/
}
In you PHP code, you are not executing the INSERT query. You need to do something like this:
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
mysql_query($sql) or die(mysql_error());
//--------Now check out the transaction status of the Inserted data---------||
Notice the line I added, which actually executes the query.
Now of course you should upgrade your code to mysqli or mysqlPDO since the PHP mysql package is not supported anymore.
If you want to use JSON in android for server purposes. like if you want to send data and retrieve a response from the server, then You have to use the JSON in accurate manner which have been defined in this link Json in Android

User Authentation using php and mysql

guys i am working on android 2.2 i am stuck where the user need to be authenticated with his use name and password
below is my code
PHP code:
<?php
$un=$_POST['userid'];
$pw=$_POST['password'];
mysql_connect("localhost","root","");
mysql_select_db("myhealthcare");
$sql=mysql_query("select userid,password from register where userid='$un' and password='$pw'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Java Code:
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("userid", userid.getText().toString()));
nvp.add(new BasicNameValuePair("password", password.getText().toString()));
String un = userid.getText().toString();
String pass = password.getText().toString();
System.out.println("user name is " + un);
System.out.println("password is " +pass);
// Log.e(""+sid.getText().toString(),"0");
// Log.e(""+sname.getText().toString(),"0");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(bf.readLine()+ "\n");
String line="0";
while ((line = bf.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("value of result " +result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String unm,pwd;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
unm = json_data.getString("userid");
pwd = json_data.getString("password");
System.out.println("databse user name is " +unm);
System.out.println("databse password is " +pwd);
}
} catch(JSONException e1){
Toast.makeText(getBaseContext(), "No details Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
i am able to fetch the value from database but i am not able to compare with user entered values please help
I would do the PHP sometheing like this instead, to do the authentication on the server and not passing the login info back and forth:
<?php
$un=mysql_real_escape_string($_POST['userid']);
$pw=mysql_real_escape_string($_POST['password']);
mysql_connect("localhost","root","");
mysql_select_db("myhealthcare");
$result=mysql_query("select userid from register where userid='$un' and password='$pw'");
if (mysql_num_rows($result) == 0) {
print("Not authorized"); // Or send a json-encoded object containing the message
} else {
print("Authorized");
}
mysql_close();
?>
Update
Use PHP's mysql_real_escape_string() before running any data input by a user in your SQL. Otherwise you open your DB to SQL-injections, which is really bad.

Android mysql php problem

I have an application which gets some data from a remote database.
I use PHP with the following code to connect to the data base.
mysql_connect($host,$username,$password) or die( "no connection");
#mysql_select_db($database) or die( "Unable to select database");
$query = $_REQUEST['query'];
$q=mysql_query($query);
while($e=mysql_fetch_assoc($q)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close();
I then connect via following java code
public void connect(ArrayList<NameValuePair> nameValuePairs) {
result = "";
InputStream is = null;
String url = "http://'ipadress'/PhpProject1/EmptyPHP.php";
//Get the content
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("Connect", "Error in http connection " + e.toString());
}
//Convert content toString
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//result = replaceString(sb.toString());
} catch (Exception e) {
Log.e("Connect", "Error converting result " + e.toString());
}
}
When i have done that I make a query through
public void query(String query){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", query));
connect(nameValuePairs);
}
While this works great with the emulator there is a problem when using it on the phone.
Anyone has a clue why this is?
Thank you in advance
Make sure to connect your real device to the your private network to actually be able to access that server.
Easiest option would be a WiFi network in the same subnet as the server. Otherwise your phone won't be able to access the network as it is not public.

Categories