简体   繁体   English

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

[英]How to get user id from XAMPP database for Android Studio

I'm creating an Android app that has login and register pages. 我正在创建一个具有登录和注册页面的Android应用。 After someone has logged in, they can do different tests provided by the app. 有人登录后,他们可以执行该应用程序提供的不同测试。 How do I get their results to be stored with their user ID in the XAMPP database? 如何将他们的结果与他们的用户ID存储在XAMPP数据库中? I have provided the login.php, LoginActivity.java, User.java and EditProfile.java code. 我提供了login.php,LoginActivity.java,User.java和EditProfile.java代码。 I have provided an example where someone might want to edit their profile and when they want to save the changes, it should be saved with their user ID. 我提供了一个示例,其中某人可能要编辑其个人资料,并且当他们要保存更改时,应将其与用户ID一起保存。 I'm struggling with it. 我正在努力。 Any help would be greatly appreciated, thank you 任何帮助将不胜感激,谢谢

login.php 的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 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 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 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);
    }
}

I would like to share some of my experience here about how I solve my problem in my project 我想在这里分享一些我如何解决项目中的问题的经验

Firstly,in order for me to get the User Id from the database,I will parse the userID value from my login.php using JSON. 首先,为了让我从数据库中获取用户ID,我将使用JSON从我的login.php中解析userID值。

Here is the login.php look like,read the comment of the code 这是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);
}
?>

So now you can get your UserID at your processFinsh() 因此,现在您可以在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();
            }

        }

At your User.java,create a getter and setter to store your user ID 在您的User.java中,创建一个getter和setter来存储您的用户ID

        private String userId;

        public String getUserId(){
            return userId;
        }

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

I dont know where you want to use your User Id,but whenever you want to use it you can call like this 我不知道您想在哪里使用用户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

In order for you have some basic concept to work with json encode,you can take a look for the below link 为了使您具有使用json编码的一些基本概念,您可以查看以下链接

How to connect Android with PHP, MySQL for Basic CRUD 如何将Android与PHP,MySQL连接以进行基本CRUD

Android Login and Registration with PHP, MySQL and SQLite 使用PHP,MySQL和SQLite进行Android登录和注册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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