简体   繁体   中英

Android login register sql

Please, can someone look at my code?I cant' find a mistake. When I try login in the app a get Toast message "Bad responses from server".I think I make some mistake in php code.Before I add validation everything work.

PHP Login In next step i want add some basic token authorization.

<?php
$con = mysqli_connect("xxxxx", "xxx", "xxx", "xxx");

$username = $_POST["username"];
$password = $_POST["password"];




$result = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
$affected = mysqli_affected_rows($con);
$response = array();
$response["success"] = false;  
$response["status"] ="INVAILD";

if ($affected > 0) {

$response["success"] = true;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
      $response["id"] = $id;
    $response["username"] = $username;
    $response["email"] = $email;
    $response["password"] = $password;
}
}
 else{
 $userCheck = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = 
'$username'");
$userAffected = mysqli_affected_rows($con);
if($userAffected>0){
$response["status"]="PASSWORD";
}
}echo json_encode($response);
mysqli_close($con);
exit();
?>

Java I created my login application using Volley, php, MYSQL

public class LoginActivity extends AppCompatActivity {
TextInputLayout tlUsername, tlPassword;
Button bLogin;
TextView tvSign;
String username, password;

RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    setTitle("Login");
    initialize();

    requestQueue = Volley.newRequestQueue(LoginActivity.this);
    tvSign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent regintent = new Intent(LoginActivity.this, 
    RegisterActivity.class);
            startActivity(regintent);

        }
    });
    bLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            username = tlUsername.getEditText().getText().toString();
            password = tlPassword.getEditText().getText().toString();

            if (validateUsername(username) && validatePassword(password)) { 
       //Username and Password Validation

                final ProgressDialog progressDialog = new 
      ProgressDialog(LoginActivity.this);
                progressDialog.setTitle("Please Wait");
                progressDialog.setMessage("Logging You In");
                progressDialog.setCancelable(false);
                progressDialog.show();


                LoginRequest loginRequest = new LoginRequest(username, password, new Response.Listener<String>() {


                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onResponse(String response) {
                        Log.i("Login Response", response);
                        progressDialog.dismiss();
                        //   json obcejt
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            if (jsonResponse.getBoolean("success")) {
                                Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);

                                Long userId = jsonResponse.getLong("id");
                                String username = jsonResponse.getString("username");
                                User user = new User(userId, username);
      // from server to  activity
                                myIntent.putExtra(MainActivity.USER_ID, userId);
                                myIntent.putExtra(MainActivity.USER, user);

                                startActivity(myIntent);
                                Toast.makeText(LoginActivity.this, "Log in",
                                        Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                if (jsonResponse.getString("status").equals("invaild"))
                                    Toast.makeText(LoginActivity.this, "User Not Found",
                                            Toast.LENGTH_SHORT).show();
                                else {
                                    Toast.makeText(LoginActivity.this, "Password dont't match",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(LoginActivity.this, "Bad Response From Server", Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        if (error instanceof ServerError)
                            Toast.makeText(LoginActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
                        else if (error instanceof TimeoutError)
                            Toast.makeText(LoginActivity.this, "Connection Timed Out", Toast.LENGTH_SHORT).show();
                        else if (error instanceof NetworkError)
                            Toast.makeText(LoginActivity.this, "Bad Network Connection", Toast.LENGTH_SHORT).show();
                    }
                });
                requestQueue.add(loginRequest);

            }
        }
    });

}
private void initialize() {
    tlUsername = (TextInputLayout) findViewById(R.id.tl_etUsername);
    tlPassword = (TextInputLayout) findViewById(R.id.tl_etPassword);
    tvSign = (TextView) findViewById(R.id.tvSign);
    bLogin = (Button) findViewById(R.id.bLogin);
}

    private boolean validateUsername(String string) {

    if (string.equals("")) {
        tlUsername.setError("enter username");
        return false;
    } else if (string.length() > 10) {
        tlUsername.setError("max 10 ");
        return false;
    } else if (string.length() < 6) {
        tlUsername.setError("Min 6 characters");
        return false;
    }
    tlUsername.setErrorEnabled(false);
    return true;
}

    private boolean validatePassword(String string) {

    if (string.equals("")) {
        tlPassword.setError("Enter Your Password");
        return false;
    } else if (string.length() > 10) {
        tlPassword.setError("max 10 characters");
        return false;
    } else if (string.length() < 8) {
    tlPassword.setError("minimum 8 characters");
    return false;
    }
    tlPassword.setErrorEnabled(false);
    return true;
      }
    }

you are going wrong there, fetch the data from database like this

 correct form will be like this,



$result = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");

and here,

 while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
  $response["id"] = $id;
$response["username"] = $row['username']; // username is your database table column name
$response["email"] = $row['email']; // same applies for email 
$response["password"] = $row['password']; // like that here also 

}

and over here

else{

$userCheck = mysqli_query($con, "SELECT * FROM users WHERE username = '$username'");

make it like this

else{

$userCheck = mysqli_query($con, "SELECT * FROM users WHERE username = '%".$username."%'");

I highly recommend you to use PDO prepare statements for security reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM