I am trying to POST data from my android to my sql server
This is in my android application
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstName",value));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
This is my php
$firstName = $_POST["firstName"];
$sql = "SELECT firstName FROM `colleague` WHERE `lastName`
LIKE '%$firstName%' LIMIT 0, 5 ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) $output[] = $row['firstName'];
echo implode("<br/>",$output);
print(json_encode($output));
But this now selects the first five rows .. it does not receive anything in $firstName = $_POST["firstName"]; ??
php Notice
Undefined index: firstName in C:\xampp\htdocs\
http declaration
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.1/Search.php");
$firstName = $_POST['firstName']; try single quotations. do you have spaces in the value for $firstName? if it is encoded, do decoding in php. Example if you have Your(space)Name then encoded form will be Your+Name, if you dont decode it the query has encoded value for $firstName. Use urldecode($_POST['firstName']) to decode the encoded url content
Related
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.
I have the following problem:
I have set up a database using XAMPP and I've written 4 PHP-Scripts to insert and show the content of it. That works fine by now. The database has two columns body and address both of type text and it is there to write some sms data in it.
Now I want to insert from my Android app. To achieve this, I have written those few lines of code inside my app:
//the sms to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("body","testbody"));
nameValuePairs.add(new BasicNameValuePair("address", "testaddress"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/sms/addsms.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
Now the problem is - if the code above has no fault - how can I pass those BasicNameValuePairs into my PHP variables? My PHP script for this looks like the following:
<?php
//This is my problem: How can I write the values from inside
//my android application in to those variables here? :(
//Getting the JSON data sent by the android app
$json_body = $_REQUEST['body'];
//Converting it into a standard class object
$obj_body = json_decode($json_body, true);
//Getting the value associated to the 'body' property
$body = $obj_body->'body';
//Getting the JSON data sent by the android app
$json_address = $_REQUEST['address'];
//Converting it into a standard class object
$obj_address = json_decode($json_address, true);
//Getting the value associated to the 'body' property
$address = $obj_address->'address';
//Connecting to database
require_once('mysqli_connect.php');
//Defining the query for inserting
$query = "INSERT INTO sms (body, address) VALUES (?,?)";
//Preparing the statement to be executed
$stmt = mysqli_prepare($dbc, $query);
//Binding the parameters to the statement
mysqli_stmt_bind_param($stmt, "ss", $body, $address);
//Executing the statement
mysqli_stmt_execute($stmt);
?>
I can run the app on the emulator, but nothing happens, so I get no new entry in my database. Can someone explain to me, how I get this right in PHP? Or is there a fault in the android code?
rikojir
I am trying to retrieve specific values from phpmyadmin database.I want to retieve the row where to=$username from mytasksend table.
But when i echo the variable i don't get any output.
What am i supposed to do?
Here's my php file
<?php
mysql_connect ("localhost","root","");
mysql_select_db("taskmanager");
$username= (isset($_POST['to'])) ? $_POST['to'] : '';
$q=mysql_query("SELECT `tasksentid` FROM `mytasksend` where `to` = $username") or die(mysql_error());
$output=array();
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
and here's my java file
try{
HttpClient httpclient3 = new DefaultHttpClient();
HttpPost httppost3 = new HttpPost("http://10.0.2.2:80/selection.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("to",id));
Log.w("aaaaaaa",""+nameValuePairs);
httppost3.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient3.execute(httppost3);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
Try wrapping the $username under single quotes in the query.
"SELECT `tasksentid` FROM `mytasksend` where `to` = '$username'"
I'm no android expert, but looking at your PHP, shouldn't you have quotes around $username? You should also really validate/clean any data coming via $_POST
I am a beginner in Android and I have the following code:
(On the PHP side, after the user logs into my Android App)
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM users WHERE c_name='$username' AND c_password='$password'") or die("Could not run query!");
$rows = mysql_num_rows($query);
if($rows == 0){
echo "No user was found";
}else{
$row = mysql_fetch_assoc($query);
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['c_name'];
echo "User Found";
}
In the file where I want to obtain the ID of the user whom was logged in I have:
session_start();
$r_name = $_POST['r_name'];
$r_address = $_POST['r_address'];
$r_phone = $_POST['r_phone'];
$r_username = $_POST['r_username'];
$req_id = $_SESSION['id'];
$req_username = $_SESSION['username'];
$query_add = "INSERT INTO data_collection VALUES ('','$r_name','$r_address','$r_phone','$r_username','$req_id')";
$query_exec = mysql_query($query_add) or die("Could not insert to db");
if($query_exec){
echo "Success";
}else
echo "Error in query";
And the Android side that posts the data to the 2nd php file:
public void onClick(View v) {
// TODO Auto-generated method stub
String s_res_name = res_name.getText().toString();
String s_res_address = res_address.getText().toString();
String s_res_phone = res_phone.getText().toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("r_name", s_res_name));//c_name is the value in PHP and in the mySQL db
nameValuePairs.add(new BasicNameValuePair("r_address", s_res_address));
nameValuePairs.add(new BasicNameValuePair("r_phone", s_res_phone));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/thesis/data_collection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,responseHandler);
tv.setText(""+response);
if (response.equals("Success")){
Toast toast = Toast.makeText(getApplicationContext(), "Data Collection task successfully created", Toast.LENGTH_LONG);
toast.show();
finish();
}
}catch(Exception e){
Log.e("log.tag","Error in http connection"+e.toString());
}
}
});
How can I obtain the session ID in the second php file and store it in a new table?
This code runs well through the web, when I post the data through a form, but on the android side it doesn't...
Thank you for your help.
How can I obtain the session ID in the second php file and store it in a new table?
The session ID is part of the request. If you mean $_SESSION['id'] you need to call session_start() first or have session auto-start configured.
Do I have to do sth on the Android side? Thank you for your help.
Yes, you need to pass the real session ID (not that $_SESSION['id'] value), it's a cookie or a query-parameter commonly named PHPSESSID by default. See also session-name. If you don't pass that info with the request, PHP does not know which session this request should belong to.
For more info, please continue here: http://php.net/sessions
In my applications I do it this way:
I have PHP script, that do real login. This script return string as "HTML page". That page is erad within application, string is parsed and data from that string are used in application for login.
Example of return string:
nick|user_id|hashed_security_string
Now in nick you have user name, user_id is his ID from DB and hashed_security_string is something used for security purposes when you for example commit something from your app to DB, this string is send with data and controlled on server if user is really logged or if user exist.
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);