I am trying to make a register app using Eclipse. I want the user to be able to fill in information in the app and click a button that will send the information to a PHP website.
However, it seems that when I click the button it doesn't send the information (display name, username and password) to the website.
Here are the lines of code of the app:
public class MainActivity extends ActionBarActivity {
EditText displayname, username, password, responseText;
String displaynameText, usernameText, passwordText;
Button registerbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
displayname = (EditText) findViewById(R.id.editText1);
username = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText3);
responseText = (EditText) findViewById(R.id.responseLog);
registerbtn = (Button) findViewById(R.id.button1);
displaynameText = displayname.getText().toString();
usernameText = username.getText().toString();
passwordText = password.getText().toString();
final HttpClient httpClient = new DefaultHttpClient();
final HttpPost httpPost = new HttpPost("http://anschluss.webuda.com/register.php");
final List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("displayname", displaynameText));
nameValuePair.add(new BasicNameValuePair("username", usernameText));
nameValuePair.add(new BasicNameValuePair("password", passwordText));
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch(UnsupportedEncodingException e){
e.printStackTrace();
}
try{
HttpResponse response = httpClient.execute(httpPost);
responseText.setText(response.toString());
} catch(Exception e){
e.printStackTrace();
}
}
});
}
As for the PHP I have this:
<?php
if(isset($_POST)){
$displayname = $_POST["displayname"];
$username = $_POST["username"];
$password = $_POST["password"];
if(!empty($displayname) && !empty($username) && !empty($password)){
$mysql_host = "hostname";
$mysql_database = "database";
$mysql_user = "username";
$mysql_password = "password";
mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database);
$checkDisplayName = mysql_query("SELECT displayname FROM info WHERE displayname = '$displayname'");
$displayNameAantal = mysql_num_rows($checkDisplayName);
$checkUsername = mysql_query("SELECT username FROM info WHERE username = '$username'");
$usernameAantal = mysql_num_rows($checkUsername);
if($displayNameAantal == 0){
if($usernameAantal == 0){
$insertQuery = mysql_query("INSERT INTO info(displayname, username, password) VALUES ('$displayname', ' $username', '$password')");
$returnValue = "Succes";
echo $returnValue;
} else{
$returnValue = "Username is already taken";
echo $returnValue;
}
} else{
$returnValue = "Displayname is already taken";
echo $returnValue;
}
} else{
$returnValue = "Something is left blank";
echo $returnValue;
}
}
?>
Please let me know if you know how to make this work.
There's something conceptually very wrong in your code: You are accessing the network inside the UI thread (=== blocking the user interface). Check if Android isn't complaining about that! Network access must be done in a thread outside the UI, using an AsyncTask (Android's preferred way) or manually spawning a Thread (classic Java way).
If there are no other errors related to the HTTP Post, probably this is what's happening. However, if you fix other possible errors and the HTTP post is sent, you will get a Called From Wrong Thread exception.
response.toString() is incorrect try using this to get the response:
EntityUtils.toString(response.getEntity(), "UTF-8");
Related
I wrote a code to receive POST variables from android clients. When the POST request is made in the Android side, the PHP will receive each variable and take next processes.
<?php
if (isset($_POST['tag']) && !empty($_POST['tag'])) {
$tag = $_POST['tag'];
// get the variables.
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// response Array
$response = array();
require_once 'mysql/DB_Functions.php';
$db = new DB_Functions();
// check for tag type
if ($tag == 'login') {
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// check if user is already exists
if ($db->userExists($email)) {
// user already exists - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already exists";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user successfully saved to MySQL database.
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Operation failed due to the missing tag!";
echo json_encode($response);
}
var_dump($_SERVER['REQUEST_METHOD'], $_POST);
?>
But when I opened this raw PHP file on the web to see how it looks, I found something very weird. It says as follows.
{"error":true,"error_msg":"Operation failed due to the missing tag!"}string(3) "GET" array(0) { }
that "GET" is the one I think very weird, because on either PHP or the Android side I never used the GET methods and it is present on the browser. How does this happen and what do I have to do to change that into POST?
edited:
Here's the Android part that requests a POST method. Volley library is used here.
Map<String, String> params = new HashMap<>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, ServerURL.URL_REGISTER, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG_REGISTER, "Register Response: " + response.toString());
pDialog.dismiss();
try {
JSONObject jObj = new JSONObject(response.toString());
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUserIntoSQLite(name, email, uid, created_at);
Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch main activity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
startActivity(intent);
getActivity().finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG_REGISTER, "Registration Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(jsonObjectRequest);
}
As mentioned in the comments, you can't just open the file in the browser and expect POST request to happen. You can only achieve GET request using that method.
I'm not sure why you're method is not working but given that your IF statement is failing you can easily test what kind of data is being passed through. Try doing the following before your first IF condition:
var_dump($_POST);
echo '=====';
var_dump($_GET);
This way you'll be able to tell what kind of data is being passed through when you make your POST request. From there you can debug and adjust your IF condition as that seems to be the main problem.
I made a post request with the following code in Android using Volley.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, ServerURL.URL_REGISTER, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG_REGISTER, "Register Response: " + response.toString());
pDialog.dismiss();
try {
JSONObject jObj = new JSONObject(response.toString());
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUserIntoSQLite(name, email, uid, created_at);
Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch main activity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
startActivity(intent);
getActivity().finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG_REGISTER, "Registration Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
Now here's the PHP part that receives the post request and get the post values.
<?php
session_start();
if (!empty($_POST['tag'])) {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'mysql/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "error" => FALSE);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed
if ($db->userExists($email)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already exists";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Operation failed due to the missing tag!";
echo json_encode($response);
}
var_dump($_SERVER['REQUEST_METHOD'], $_POST);
?>
I should be able to get the 'tag' value, but the problem is that it keeps saying that the 'tag' is missing.
So now I created an HTML file to test which part has a problem.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="index.php" method="post">
Tag: <input type="text" name="tag"><br>
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
As I put the data in this HTML file, the data is successfully stored in the MySQL database. Which part do you think has the problem?
I've searched all the solutions regarding the Volley part, and my Volley part doesn't seem to have the problem. So I believe it's the PHP part that's causing the issue.
If I open the PHP file on the web, it shows the following message.
{"error":true,"error_msg":"Operation failed due to the missing tag!"}string(3) "GET" array(0) { }
The problem is that you are sending data from the Volley library as content type application/json but your PHP script is expecting POST data as content type application/x-www-form-urlencoded. This is why your POST from the web form worked, but your POST from Volley did not.
In your PHP script, do this:
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['tag']) == false) {
$tag = $data['tag'];
echo $tag;
}
Because you're sending the data as JSON, PHP won't automatically parse it into the $_POST global. What the code above does is get the raw POST data as a string and parse it into an array.
Update
I spent some more time debugging this and now have a full solution:
PHP:
Change your script to access the raw POST data using the method I listed above, instead of $_POST global. Use this code for debugging purposes:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['tag']) == false) {
$tag = $data['tag'];
}
echo json_encode([ "tag" => $tag ]);
?>
Android:
getParams() is apparently not used with JsonObjectRequest class, so your body is empty. See the answer to this question for details of that. Instead, you must pass your body as a JsonObject in the constructor to JsonObjectRequest. For example:
HashMap<String, String> params = new HashMap<>();
params.put("tag", "register");
params.put("name", "myname");
params.put("email", "myname#email.com");
params.put("password", "meow");
JSONObject o = new JSONObject(params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
ServerURL.URL_REGISTER,
o,
new Response.Listener<JSONObject>() { // ...
Result:
D/EXAMPLE: Register Response: {"tag":"register"}
I've created a more complete example as a gist.
Note: If you are making requests to a development server on your local machine, you'll need to use 10.0.2.2:PORT instead of localhost:PORT. I'm assuming that this is not an issue in your case, since you seem able to connect to your server, but include this note for completeness for any future readers.
my code inserts an empty field when i try to run it from the android emulator.
the php script is fine, when i replace the variables with actual values it works.
when i run the script itself, it sends a row to my database, which is blank.
<?php
$connect = mysql_connect("localhost","","") or die(mysql_error());
mysql_select_db("tedd_fyp") or die(mysql_error());
$username = $_POST['username'];
$password = $_POST['password'];
$query="INSERT INTO name (username, password) VALUES ('$username' ,'$password')";
$res = mysql_query($query) or die ("Error: ". mysql_error(). " with query ");
mysql_close($connect);
echo $res;
?>
this is my java code, which can't connect to my php script.
when i run this script, nothing happens.
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
Button registerLecturer=(Button)findViewById(R.id.button1);
registerLecturer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String username = editText1.getText().toString();
String password = editText2.getText().toString();
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://tedd.5gbfree.com/insert.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
I have written PHP code to fetch data from Database. It get the login values. (username & password). I connect it through mysql server/localhost. when I run this PHP code it always show the "0". It means it doesn't get the data from Database. Why is that?
Here my PHP code:
<?php
$hostname_localhost ="localhost";
$database_localhost ="gpsvts_geotrack";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['uname'];
$password = $_POST['passwd'];
$query_search = "select 'uname' & 'passwd' from user_master where uname = '.$username.' AND passwd = '.$password.'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
I put this in my wamp server www folder.when i run this php file wamp server localhost it always say "no such user found".
i used this php file for fetching data from db to connect android login form. it contain two fields. which are username & password.
here I give my android login code.
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2//new/nuwan1.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
Always I got the alart no such user found & php response is No such user found
why is that?
pls help me.
I used following php code
<?php
$un=$_POST['uname'];
$pw=$_POST['passwd'];
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM $tbl_name WHERE uname = '$un' AND passwd= '$pw'";
//$query = "SELECT uid FROM $tbl_name WHERE uname = '$un' AND passwd = '$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 mysql_result($result,0); // for correct login response
else
echo 0; // for incorrect login response
?>
Then return uid as response. but not validating user. Is there PHP code wrong or android code wrong. I want to match the values user enter & database get. Is that happen in here.
if not give me correct thing.
In your program you are passing from your side is:
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
And you are trying to fetch from PHP side is:
$un=$_POST['uname'];
$pw=$_POST['passwd'];
So Change The Name in nameValuePairs are passed with this:
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
If I'm not mistaken it should be like this because your post variables are spelled different than what you're putting in the name value pairs.
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
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!