Inserting into a database via Android - php

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

Related

Why can't I get a value in php from android?

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

HTTP Post not working with PHP in android

I learning android and trying to write some code to verify a username and password using a PHP script and a WAMP server. I keep getting undefined index errors from my PHP script. As far as I can ascertain that means my PHP script can't access the data from the URL. Here is the relevant code. Any help is appreciated.
//build url data to be sent to server
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
Here is my PHP script
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
$username = $_POST["username"];
$suppliedPassword = $_POST["password"];
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
And here a picture of the server's reply
http://imgur.com/sQStI2D
EDIT: So I figured out that even though the PHP script is giving these errors the $username and $password variables contain the values my android app was attempting to pass along. However the presence of these errors is still messing with my code because the HTML for the error tables gets sent back to the android app in the response
To me it looks like your Android code isn't POSTing the "username" and "password" fields, that explains why the PHP script can't find them.
In your code, new ArrayList<NameValuePair>();, the length of the arrayList may be missing, by looking at this code sample: it looks like it should be new ArrayList<NameValuePair>(2);, you should try with that and see if resolves the issue.
Turns out it was a simple spelling error. I used a lower case 'p' in the word 'password' in my loop instead of an uppercase. Odd that it caused the error that it did.
You can try json_decode() function in PHP:
try to create A file on your server and put content of android request into simple text file you will get array output. in that file.
on your server in .php file write below code:
<?php
$data=file_put_content(collect.txt, $_POST);
// if you got to know object or array name from txt file use it.
$array=json_decode($data, true) // for array output.
print_r($array);
?>
and if you don't want to read from file you can directly use if you know array name, in json object
<?php
$array=json_decode($data) // remove true for use as an object output.
print_r($array);
?>
once you got your array assign values to new variables and do whatever you want with them. Update database or anything as per your requiremnet

Android PHP - Store Session to mySQL DB

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.

Android - Values not being stored into MySQL database through php

I am sending some values through HTTP Post to my server from my Android emulator but the values are not being stored. My logcat is showing response code 200 and displaying the codes of the php script as a http response. My database is fine as i am able to insert data in it. Any idea what might be the matter?
main.java
public void sendRegistrationIdToServer(String deviceId,
String registrationId) {
System.out.println(registrationId);
System.out.println(deviceId);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.21.78.11/storePost.php?");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
nameValuePairs.add(new BasicNameValuePair("devid", deviceId));
nameValuePairs.add(new BasicNameValuePair("regid",
registrationId));
//HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("HTTP Status = "+status);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
storePost.php
<?php
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("DeviceID");
$regid = mysql_real_escape_string($_POST["regid"]);
$devid = mysql_real_escape_string($_POST["devid"]);
mysql_query("INSERT INTO Android(regID, devID) VALUES ('$regid', '$devid')") or die(mysql_error());
mysql_close();
?>
Make sure your web server is configured to run php codes. If you go to storePost.php with your desktop browser and you still see the codes displayed in the browser, then it's a configuration issue with your webserver. Until you fix that, the Android code will still be returning php codes as a response.
If you're on a windows platform, you might want to check this out http://www.simplehelp.net/2008/08/25/how-to-install-and-setup-apache-mysql-and-php-in-windows/
or linux https://help.ubuntu.com/community/ApacheMySQLPHP
Even easier, check xampp out www.apachefriends.org/en/xampp.html

trying to send data using POST from android to sql

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

Categories