我一直在研究这个问题。我尝试的第一件事是将登录用户存储在会话中,然后尝试稍后使用该变量,如下所示:
的login.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sessionid = session_id();
require_once('connect.inc.php');
$sql = "SELECT username, password FROM USER WHERE username = ?";
$stmt = $conn->prepare($sql);
$username = $_POST["username"];
$password = $_POST["password"];
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($user, $pass);
while($stmt->fetch()){
$verify = password_verify($password, $pass);
}
if($verify){
$_SESSION["username"] = $username;
echo 'connected';
echo $sessionid;
}else{
echo 'check details';
}
mysqli_close($conn);
}
?>
然后我在消息中获取登录的响应并将其拆分为两个变量。登录响应和会话ID。我将会话ID和存储在共享首选项中。我试图将会话ID存储在我的java方法中,以便我可以访问会话用户。这是我尝试获取用户的java代码:
GetUserData Java方法
private void getUserData() {
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
String sessionId = sharedPreferences.getString(Config.SID, "SessionID");
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.SERVER_ADDRESS + "GetUserData.php?PHPSESSID=" + sessionId,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
//json string to jsonobject
jsonObject = new JSONObject(response);
//get json sstring created in php and store to JSON Array
result = jsonObject.getJSONArray(Config.json_array);
//get username from json array
getUserInfo(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getUserInfo(JSONArray jsonArray){
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
userInfo.add(json.getString(Config.getUsername));
} catch (JSONException e) {
}
}
}
这是java方法试图调用的php文件:
GetUserData.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$username = $_SESSION['username'];
$sql = "SELECT * FROM USER WHERE username = '$username'";
require_once('connect.inc.php');
$run = mysqli_query($conn, $sql);
$result = array();
while($row = mysqli_fetch_array($run)){
array_push($result, array(
'id' => $row['id'],
'fname' => $row['fname'],
'lname' => $row['lname'],
'username' => $row['username'],
'email' => $row['email'],
));
}
echo json_encode(array('result'=>$result));
mysqli_close($conn);
}
?>
调试时,'result'数组为空,因此出于某种原因,
$sql = "SELECT * FROM USER WHERE username = '$username'";
无效。我知道它与会话有关,但我不确定问题出在哪里。
我的下一次尝试是尝试将登录用户存储在共享首选项中,然后从php文件中调用该变量并运行查询以显示该变量的用户信息。我该怎么做?
谢谢。
答案 0 :(得分:0)
当您在此处输入用户名和密码到服务器时,您要做的是发送请求。注意我修改了你的代码。
String enteredUsername =&#34; username&#34 ;; String enteredPassword =&#34; xxxxxx&#34 ;;
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s", enteredUsername, enteredPassword);
StringRequest stringRequest = new StringRequest(Request.Method.GET, uri,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
// parse the response object and store user id and data in sharedpreference.
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
检查用户是否尚未注册,将用户添加到数据库并返回用户数据库唯一ID以及您想要的其他数据。
然后将用户ID和用户名保存到SharedPreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
sharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("Personal Information", set);
edit.commit();
首先应检查是否优先存储用户ID,以确定用户是否为注册用户。如果用户未注册,则显示登录表单,否则将用户重定向到个人资料活动页面。
答案 1 :(得分:0)
我已经有一个登录类,可以确保用户已注册。我只是想按照我的说法从数据库中获取用户信息。这是我可能应该提供的登录方法:
private void login(){
final String username = txtUsrnm.getText().toString().trim();
final String password = txtPswrd.getText().toString().trim();
//create string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.SERVER_ADDRESS + "Login.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String responseOne = response.substring(0,9);
String responseTwo = response.substring(9);
if(responseOne.equalsIgnoreCase(Config.logInMessage)){
//create shared pref
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
//editor stores values to the shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
//add values
editor.putBoolean(Config.sharedPrefBool, true);
editor.putString(Config.username, username);
editor.putString(Config.password, password);
editor.putString(Config.SID, responseTwo);
editor.commit();
Intent intent = new Intent(Login.this, Home.class);
startActivity(intent);
}else{
//display error message
Toast.makeText(Login.this, "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//from android.com: A Map is a data structure consisting of a set of keys and
// values in which each key is mapped to a single value. The class of the objects
// used as keys is declared when the Map is declared, as is the class of the
// corresponding values.
Map<String,String> hashMap = new HashMap<>();
//maps specified string key, username and password, to specified string value
hashMap.put(Config.username, username);
hashMap.put(Config.password, password);
return hashMap;
}
};
//add string request to queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}