Android - Values not being stored into MySQL database through php - 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

Related

httpURLConnection to php server gives different response (url works on web browser)

The code requests HTTP connection to server that runs with php (phpMyAdmin).
It gives response with JSONObject.
It worked when I was testing in Asia, however it gives different response in the United States.
With given url:
target = "http://example.com/request.php?value=DDPS"
This works on web browser but in Android device it gives:
<html><body><script type="text/javascript" src="/cupid.js"></script><script>
.....path=/";location.href="http://example.com/request.php?value=DDPS
&ckattempt=1";</script></body></html>
This fails to create JSONObject which is obvious.
What would be possible problem on this behavior?
I have set permission to server that allows access from all continents.
Here is my httpURLconnection code:
try{
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setInstanceFollowRedirects(true);
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while((temp = bufferedReader.readLine()) != null)
{
stringBuilder.append(temp).append("\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}catch (Exception e) {
e.printStackTrace();
}
EDIT:
HttpURLConnection.setFollowRedirects(true);
gives same behavior.
Here is my php code for getting data from database and send response in JSON format.
On which point should I implement file_get_contents?
<?php
header("Content-Type: text/html; charset=UTF-8");
$con = mysqli_connect("localhost", "exampleID", "examplePW", "exampleID");
$value = $_GET["title"];
$result = mysqli_query($con, "SELECT * FROM DB WHERE title = '$value'");
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("item1"=>$row[1], "item2"=>$row[2], "item3"=>$row[3], "item4"=>$row[4]));
}
echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
probably issue with server redirects. Android gets the first response. you could verify it with using a php scropt and file_get_contents method
You can also try
HttpURLConnection.setFollowRedirects(true);
Solved.
There was no issue in android codes.
The issue was from the server I was connecting to.
It blocked some unknown IP addresses, so I needed to give permission to server to accept certain IP access.

Returning specific number of values from php to Android

I'm experiencing troubles with my android code. I'm trying to plot a graph within Android. I want to connect to MySQL base using PHP script. I'm trying to send some parameters to script, but it keeps returning null.
PHP code:
<?
mysql_connect(...);
mysql_select_db("temperature");
$Vreme = $_POST['Vreme'];
$Datum = $_POST['Datum'];
$q = mysql_query("SELECT * FROM temperature WHERE
((datum > $Datum) || (datum = $Datum)) && (vreme > $Vreme) ");
while($e = mysql_fetch_assoc($q))
$output[] = $e;
print(json_encode($output));
mysql_close();
?>
And Android code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Vreme",s1));
nameValuePairs.add(new BasicNameValuePair("Datum",s2));
InputStream is = null;
try {
String adresa="http://senzori.open.telekom.rs/grafik.php";
HttpPost httppost = new HttpPost(adresa);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
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();
result = sb.toString();
}
catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
Combined awnser of the comments:
1: change to mysqli or pdo (see Advantages Of MySQLi over MySQL)
2: prevent sql injection (see halfway down https://stackoverflow.com/tags/php/info)
Also when looking at your code you dont use quotes around your date (and vreme if its not numeric). Try
"SELECT * FROM temperature WHERE (datum>='$Datum' && vreme>'$Vreme')"
If it doesnt work test your page in a regular browser to make sure the PHP part works. Also you could add some var_dump() to check values.
You should try to debug the individual parts individually.
Try to connect to your php-page using a normal browser. If it works you know the error is in your java-code. If it doesn't work you could leave the java-code alone for now and focus on making the php-page work.
Hard code valid values for Datum and Vreme and see if the php-code works when leaving the POST-part out of the equation.
Try your query in mysql to see that it does what you expect before putting into php.
Enable the general query log to see what php sends to mysql.
This way you will pin point the error.

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!

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.

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