簡體   English   中英

盡管使用mysql的電子郵件和密碼的真實值仍無法登錄

[英]Can't login despite of true values of email and password with mysql

我想通過使用volley framework和SharedPreferences與mysql測試登錄應用程序。 問題是,當我輸入電子郵件和密碼的真實值時,我的響應中有success值,但我還意圖Invalid username or password ,而沒有重定向到第二個活動。

Config.java

public class Config {

    //URL to our login.php file
    public static final String LOGIN_URL = "http://10.0.3.2/test_volley/login.php";

    //Keys for email and password as defined in our $_POST['key'] in login.php
    public static final String KEY_EMAIL = "email";
    public static final String KEY_PASSWORD = "password";

    //If server response is equal to this that means login is successful
    public static final String LOGIN_SUCCESS = "success";

    //Keys for Sharedpreferences
    //This would be the name of our shared preferences
    public static final String SHARED_PREF_NAME = "myloginapp";

    //This would be used to store the email of current logged in user
    public static final String EMAIL_SHARED_PREF = "email";

    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";

}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //Defining views
    private EditText editTextEmail;
    private EditText editTextPassword;
    private AppCompatButton buttonLogin;

    //boolean variable to check user is logged in or not
    //initially it is false
    private boolean loggedIn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin);

        //Adding click listener
        buttonLogin.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //In onresume fetching value from sharedpreference
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        //Fetching the boolean value form sharedpreferences
        loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

        //If we will get true
        if (loggedIn) {
            //We will start the Profile Activity
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            startActivity(intent);
        }
    }


    private void login() {
        //Getting values from edit texts
        final String email = editTextEmail.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();

        //Creating a string request
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
            new Response.Listener < String > () {
                @Override
                public void onResponse(String response) {
                    System.out.println("response " + response); => success
                    //If we are getting success from server
                    if (response.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {

                        //Creating a shared preference
                        SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                        //Creating editor to store values to shared preferences
                        SharedPreferences.Editor editor = sharedPreferences.edit();

                        //Adding values to editor
                        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                        editor.putString(Config.EMAIL_SHARED_PREF, email);

                        //Saving values to editor
                        editor.commit();

                        //Starting profile activity
                        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
                        startActivity(intent);
                    } else {
                        //If the server response is not success
                        //Displaying an error message on toast
                        Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //You can handle error here if you want
                }
            }) {
            @Override
            protected Map < String, String > getParams() throws AuthFailureError {
                Map < String, String > params = new HashMap < > ();
                //Adding parameters to request
                params.put(Config.KEY_EMAIL, email);
                params.put(Config.KEY_PASSWORD, password);

                //returning parameter
                return params;
            }
        };

        //Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        //Calling the login function
        login();
    }
}

的login.php

<?php  
 if($_SERVER['REQUEST_METHOD']=='POST'){
 //Getting values 
 $username = $_POST['email'];
 $password = $_POST['password'];

//Creating sql query
 $sql = "SELECT * FROM user_info WHERE email='$username' AND password='$password'";

//importing dbConnect.php script 
require_once('dbConnect.php');

//executing query
$result = mysqli_query($con,$sql);

//fetching result
 $check = mysqli_fetch_array($result);

//if we got some result 
if(isset($check)){
//displaying success 
 echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
?>  

您的login.php看起來像

<?php  
if($_SERVER['REQUEST_METHOD']=='POST'){
     //Getting values 
     $username = $_POST['email'];
     $password = $_POST['password'];

    //Creating sql query
     $sql = "SELECT * FROM user_info WHERE email='$username' AND password='$password'";

    //importing dbConnect.php script 
    require_once('dbConnect.php');

    //executing query
    $result = mysqli_query($con,$sql);

    //fetching result
     $check = mysqli_fetch_array($result);

    //if we got some result 
    if(isset($check)){
    //displaying success 
      $jsonOutput['meta']['status'] = 'success';
      $jsonOutput['meta']['code'] = '200';
      $jsonOutput['meta']['message'] = "Login Successfully";
    }else{
    //displaying failure
      $jsonOutput['meta']['status'] = 'error';
      $jsonOutput['meta']['code'] = '400';
      $jsonOutput['meta']['message'] = "Invalid Username or Password";
    }
     header('Content-type: application/json');
     echo json_encode($jsonOutput);
}
?>  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM