2017-03-07 41 views
0

我正在創建一個具有登錄和註冊頁面的Android應用程序。有人登錄後,他們可以進行應用程序提供的不同測試。我如何將他們的結果與他們的用戶ID一起存儲在XAMPP數據庫中?我提供了login.php,LoginActivity.java,User.java和EditProfile.java代碼。我提供了一個例子,其中有人可能想要編輯他們的個人資料,當他們想要保存更改時,應該用他們的用戶ID保存。我正在努力。任何幫助將不勝感激,謝謝如何從Android Studio的XAMPP數據庫獲取用戶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); 
    } 
} 
+0

[Little Bobby](http://bobby-tables.com/)說*** [你的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/如何可以防止SQL注入在PHP中)***瞭解[準備](http://en.wikipedia .org/wiki/Prepared_statement)[MySQLi]的聲明(http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! [不要相信它?](http://stackoverflow.com/q/38297105/1011527) –

+0

**不要存儲純文本密碼!**請使用PHP的[內置函數](http:// jayblanchard。 net/proper_password_hashing_with_PHP.html)來處理密碼安全性。如果您使用的PHP版本低於5.5,則可以使用'password_hash()'[兼容包](https://github.com/ircmaxell/password_compat)。確保你*** [不要越獄密碼](http://stackoverflow.com/q/36628418/1011527)***或在哈希之前使用其他任何清理機制。這樣做*更改密碼並導致不必要的附加編碼。 –

回答

0

我想和大家分享一些我在這裏的經歷我如何解決我的問題,在我的項目

首先,爲了讓我能夠從數據庫中獲取的用戶ID,我會從我的登錄解析用戶ID值.php使用JSON。

這裏是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()

@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,BU只要你想噸至使用它,你可以這樣

//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編碼工作,你可以看看在下面的鏈接

How to connect Android with PHP, MySQL for Basic CRUD

Android Login and Registration with PHP, MySQL and SQLite

相關問題