0

I'm creating an Android app that has login and register pages. 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? I have provided the login.php, LoginActivity.java, User.java and EditProfile.java code. 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. I'm struggling with it. Any help would be greatly appreciated, thank you

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);
    }
}
GleneaMan
  • 167
  • 1
  • 2
  • 13
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 07 '17 at 13:02
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Mar 07 '17 at 13:03

1 Answers1

0

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.

Here is the login.php look like,read the comment of the code

 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()

@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

        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

//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

How to connect Android with PHP, MySQL for Basic CRUD

Android Login and Registration with PHP, MySQL and SQLite

ken
  • 2,426
  • 5
  • 43
  • 98