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.
Related
My app tries to create a new row in a server.
The error I get is Null Point Exception at jObj = new JSONObject(json);
This is the php file that creates a new row:
<?php
$response = array();
if (isset($_POST['user']) && isset($_POST['pass']) & isset($_POST['mail'])&& isset($_POST['num']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$mail = $_POST['mail'];
$num = $_POST['num'];
require_once __DIR__ . '/db_connect2.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO users(Name, Password, Email,ConfirmNum) VALUES('$user', '$pass', '$mail', '$num')");
if ($result) {
$response["success"] = 1;
$response["message"] = "user successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>
The parser that requests for the update is:
package com.example.denis.onthego;
import android.content.ContentValues;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class JSONParser {
static JSONObject jObj;
static String json;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method, ContentValues params) {
// Making HTTP request
try {
final OkHttpClient client = new OkHttpClient();
Request request;
// check for request method
if (method.equals("POST")) {
// request method is POST
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
request = new Request.Builder().url(url).post(body).build();
}
else {
// request method is GET
request = new Request.Builder().url(url).build();
}
final Response response = client.newCall(request).execute();
json = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e ){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And the call for the parser is :
JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params);
While the "add_user" is for the php file that makes a new row(It is the correct url) and "params" are not empty and contain the right keys and content.
Is there something wrong with the parser or the php file?
This is a very serious school project and this is the only thing I am missing.
Here are the params:
params.put("user", "swane15");
params.put("pass", "asdeg124A");
params.put("mail", "asf#asd.com");
params.put("num", "111111");
Why doesn't the php file return anything? Is because the app can't reach it or is there an error with the php file itself?
MediaType JSON = MediaType.parse("Content-Type:application/json; charset=UTF-8");
RequestBody body = RequestBody.create(JSON, params.toString());
Change to:
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
To do it right you should URLEncoder.encode() the values.
I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.
This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.
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 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");
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!