0

I am trying to sent data from my android app to php server for login .... but It respone me $success=1 and #message=login successfully .... even if I enter wrong username and password ..... can anyone help me?

if (isset($_POST['username']) && isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    echo $username;
    echo $password;



    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql checking row
    $result = mysql_query("SELECT * FROM user WHERE username = '$username' AND password = '$password'")or die(mysql_error());

    // check if row exist or not
    if ($result == true) {
        // row exist in database
        $response["success"] = 1;
        $response["message"] = "Login successfully.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // row not exist
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
    } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

on android side:

      class NewSignup extends AsyncTask<String, String, String> {

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username_editTextString));
        params.add(new BasicNameValuePair("password", password_editTextString));

        // getting JSON Object
        // Note that create product url accepts POST method
        json = jsonParser.makeHttpRequest(url_create_login,
                "POST", params);

        // check log cat fro response
        Log.i("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully login
                Intent i = new Intent(getApplicationContext(), Next.class);
                startActivity(i);

                // closing this screen
                finish();
            } else {
                // failed to login
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
Hunsu
  • 3,281
  • 7
  • 29
  • 64
Farah
  • 11
  • 4
  • You should not test with `!$result`. The function doesn't return true if success but return `False` if it fail. – Hunsu May 11 '14 at 08:08
  • You can use `echo json_encode($response);` once at the end. – Hunsu May 11 '14 at 08:09
  • It's not a good idea to store raw password in database. You must escape the data sent by the user to protect from sql injection (look at http://stackoverflow.com/questions/8263371/how-prepared-statements-can-protect-from-sql-injection-attacks) – Hunsu May 11 '14 at 08:15
  • In my first comment I mean I think you must change your test to `!$result` – Hunsu May 11 '14 at 08:17
  • yeah ...i'll do that but first I have to solve this problem using this simple code .... sorry I can't get your point of !$result.... cn u please explain? – Farah May 11 '14 at 08:17

2 Answers2

1
$result = mysql_query("SELECT * FROM user WHERE username = '$username' AND password = '$password'")or die(mysql_error());

// check if row exist or not
if ($result == true) {

This is not what you want. As said in the documentation for mysql_query, it will return a resource for SELECT statements, no matter if there are any rows in the resultset.

You can get the number of rows in the resultset returned from mysql_query by using mysql_num_rows, and what you what is probably something like this:

// check if row exist or not
if (mysql_num_rows($result) == 1) {

Also, you code is vulnerable to SQL injections. I strongly recommend you to read some information on prepared statements.

izstas
  • 5,004
  • 3
  • 42
  • 56
  • Do you get any errors? Also, sorry for a stupid question, but you didn't remove the line with the actual query (`$result = ...`), did you? – izstas May 11 '14 at 08:33
  • getting this for correct username and password and same for the wrong one ...... Create Response(18078): {"email":""} – Farah May 11 '14 at 08:41
  • I don't see any mentions of email in the code you provided so I guess you'll have to check some other parts of your code. – izstas May 11 '14 at 08:59
  • but now inlogcat ... it is showing ..... "org.json.JSONException: No value for success" ..... while TAG_SUCCESS = "success" .... in try catch code in upper mentioned android side code – Farah May 11 '14 at 09:41
0

A few pointers on your php

  1. Use mysqli - mysql is deprecated in 5.5+
  2. Use prepared statements to avoid sql injection vulnerabilities

So login code should look like

    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT username, password
                  FROM user 
                                  WHERE username = ? LIMIT 1")) {
        $stmt->bind_param('s', $username);  // Bind "$username" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($username,$db_password);
        $stmt->fetch();
        if ($stmt->num_rows == 1 && $db_password == $password)
        {
          $response["success"] = 1;
          $response["message"] = "Login successfully.";


       } else {
         // failed to find row and match password 
         $response["success"] = 0;
         $response["message"] = "Oops! An error occurred.";


}


echo json_encode($response);

To connect with mysqli use mysqli_connect http://uk3.php.net/manual/en/function.mysqli-connect.php

Shaun Hare
  • 3,771
  • 2
  • 24
  • 36