如何从Android Studio的XAMPP数据库中获取用户ID



我正在创建一个具有登录和注册页面的Android应用程序。有人登录后,他们可以进行应用程序提供的不同测试。如何在XAMPP数据库中使用其用户ID存储他们的结果?我提供了login.php,loginactivity.java,user.java和editprofile.java代码。我提供了一个示例,有人可能想编辑他们的个人资料,以及当他们想保存更改时,应使用其用户ID保存。我在努力。任何帮助将不胜感激,谢谢

login.php

<?php
    $error = NULL;
    include_once('connection.php');
        if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
        $username = $_POST['txtUsername'];
        $password = $_POST['txtPassword'];
        $query = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
        $result = mysqli_query($conn, $query);
        if($username == $error || $password == $error) {
            echo "Login Failed <br>";
        }
        else if($result->num_rows > 0){
            if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
                echo "success";
                exit;
            }
            echo "Login Successful";
        }
        else{
            echo "Login Failed <br>";
        }
    }
?>

<html>
<head>
    <title>Login</title>
</head>
<body>
<h1>Login </h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
    Username <input type="text" name="txtUsername" value="" /> <br/>
    Password <input type="password" name="txtPassword" value=""/><br/>
    <input type="submit" name="btnSubmit" value="Login"/> </form>
</body>
</html>

loginactivity.java

package com.delta.object.newandroidproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity implements       AsyncResponse, View.OnClickListener {
    EditText etUsername, etPassword;
    Button loginBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.login_toolbar);
        setSupportActionBar(mToolbar);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        loginBtn = (Button) findViewById(R.id.email_login_button);
        loginBtn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        HashMap postData = new HashMap();
        postData.put("mobile", "android");
        postData.put("txtUsername", etUsername.getText().toString());
        postData.put("txtPassword", etPassword.getText().toString());
        PostResponseAsyncTask task = new PostResponseAsyncTask(this, postData);
        task.execute("http://10.0.3.2/androidproject/login.php");
    }
    @Override
    public void processFinish(String result) {
        if (result.equals("success")) {
            Intent i = new Intent(this, TestActivity.class);
            startActivity(i);
        }
        else{
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }
    public void registerClick(View view) {
        Intent i = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(i);
    }
}

user.php

package com.delta.object.newandroidproject;
import com.google.gson.annotations.SerializedName;
public class User {
    @SerializedName("user_id")
    public int user_id;
    @SerializedName("name")
    public String name;
    @SerializedName("gender")
    public String gender;
    @SerializedName("username")
    public String username;
    @SerializedName("password")
    public String password;
 }

editprofile.java

package com.delta.object.newandroidproject;
import android.content.Intent;
import java.util.ArrayList;
import java.util.HashMap;

public class EditProfile extends AppCompatActivity {
    EditText etName, etPassword, etUsername;
    Button submitBtn;
    RadioGroup rg;
    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.edit_profile_toolbar);
        setSupportActionBar(mToolbar);
    }
    public void editProfileSave(View view) {
        Intent i = new Intent(EditProfile.this, TestActivity.class);
        startActivity(i);
    }
    public void cancelClick(View view) {
        Intent i = new Intent(EditProfile.this, TestActivity.class);
        startActivity(i);
    }
}

我想在这里分享一些我在项目中解决问题的经验

首先,为了使我从数据库中获取用户ID,我将使用JSON从我的login.php中解析用户ID。

这是login.php的样子,请阅读代码的评论

 login.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];
    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);
    if ($user != false) {
        // user is found
        //so reading all the database record 
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"]; //here is the user ID,will fetch along
        $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 is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response); //encode this to JSON,so later on can be use in Android code
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>

所以现在您可以在ProcessFinsh()

上获取USERID
@Override
        public void processFinish(JSONArray jarray) {
            // TODO Auto-generated method stub
            try{
            JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                // Check for error node in json
                if (!error) {
                    // user successfully logged in

                    // Get your user ID here and other details
                    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");
                    //Here you can set your userId to the global value,so you can use it in your EditProfile.java
                   User userId = (User)getApplicationContext();
                    userId.setUserId(uid);
                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                 }
                catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

在您的user.java上,创建一个getter和setter来存储您的用户ID

        private String userId;
        public String getUserId(){
            return userId;
        }
        public void setUserId(String user_id){
            this.userId = user_id;
        }

我不知道您想在哪里使用用户ID,但是只要您想使用它

//Get your userId
    User userId = (User)getApplicationContext();
    String userId=   userId.getUserId(); 
    Log.d("userId",userId) // log to the android monitor to see whether is the value you want or not

为了使您有一些基本概念可以与JSON编码一起使用,您可以查看以下链接

如何与PHP连接Android,MySQL以for Basic Crud

使用PHP,MySQL和SQLite

进行Android登录和注册

最新更新