How to extract json data and insert in mysql php - 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

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

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.

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

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!

Categories