簡體   English   中英

PHP / AndroidStudio-通過獲取當前用戶作為外鍵登錄進行發布

[英]PHP/AndroidStudio - Make a post by getting the current user logged in as foreign key

我正在嘗試制作新聞應用程序,我需要注冊新聞並獲取當前登錄用戶的ID作為PHP文件的參數。

我已經有登錄/注銷系統,並將其保存在“共享首選項”文件中。

我之所以問是因為我沒有足夠的知識來了解如何使用PHP和Android Studio實現這一目標。

這是我的文件,我只需要向正確的方向指出,即使是將來的參考,最好的方法是什么?

如果您願意提供幫助,請先謝謝您。

常數

public class Constants {

    private static final String ROOT_URL = "http://localhost/android/v1/";

    public static final String URL_REGISTER = ROOT_URL+"registerUser.php";

    public static final String URL_LOGIN = ROOT_URL+"userLogin.php";
}

DBO操作

<?php 

class DBOperations{

    private $con; 
    private $res;

    function __construct(){

        require_once dirname(__FILE__).'/DBConnect.php';

        $db = new DBConnect();

        $this->con = $db->connect();

    }

    /*CRUD -> C -> CREATE */

    public function createUser($username, $password, $email){
        if($this->isUserRegistered($username,$email)){
            return 0; 
        }else{
            $stmt = $this->con->prepare("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
            $stmt->bind_param("sss",$username,$password,$email);

            if($stmt->execute()){
                return 1; 
            }else{
                return 2; 
            }
        }
    }

    public function registerNews($news_post, $user_FK){

            $stmt = $this->con->prepare("INSERT INTO `news` (`id`, `news_post`, `user_FK`) VALUES (NULL, ?, ?);");
            $stmt->bind_param("sss",$news_post,$user_FK);

            if($stmt->execute()){
                return 1; 
            }else{
                return 2; 
            }
    }

}

DBRegisterUser

<?php 

require_once '../includes/DBOperations.php';

$response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(
        isset($_POST['username']) and
            isset($_POST['email']) and
                isset($_POST['password']))
        {
        //operate the data further 

        $db = new DBOperations(); 

        $result = $db->createUser(   $_POST['username'],
                                    $_POST['password'],
                                    $_POST['email']
                                );
        if($result == 1){
            $response['error'] = false; 
            $response['message'] = "User registered successfully";
        }elseif($result == 2){
            $response['error'] = true; 
            $response['message'] = "Some error occurred please try again";          
        }elseif($result == 0){
            $response['error'] = true; 
            $response['message'] = "It seems you are already registered, please choose a different email and username";                     
        }

    }else{
        $response['error'] = true; 
        $response['message'] = "Required fields are missing";
    }
}else{
    $response['error'] = true; 
    $response['message'] = "Invalid Request";
}

echo json_encode($response);

DBRegisterNews(不知道如何更改此設置)

    <?php 

require_once '../includes/DBOperations.php';

$response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(
        isset($_POST['userid']) and
            isset($_POST['email']) and
                isset($_POST['password']))
        {
        //operate the data further 

        $db = new DBOperations(); 

        $result = $db->registerNews($_POST['userid'],
                                    $_POST['password'],
                                    $_POST['email']
                                );
        if($result == 1){
            $response['error'] = false; 
            $response['message'] = "News registered successfully";
        }elseif($result == 2){
            $response['error'] = true; 
            $response['message'] = "Some error occurred please try again";          
        }

    }else{
        $response['error'] = true; 
        $response['message'] = "Required fields are missing";
    }
}else{
    $response['error'] = true; 
    $response['message'] = "Invalid Request";
}

echo json_encode($response);

注冊(供參考,正在運行)

public class SignUpActivity extends AppCompatActivity {


    private TextInputEditText editTextUsername, editTextEmail, editTextPassword, editTextConfirmPassword;
    private ProgressBar bar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        editTextUsername = findViewById(R.id.editTextLoginUsername);
        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextLoginPassword);
        editTextConfirmPassword = findViewById(R.id.editTextConfirmPassword);

        bar = findViewById(R.id.progressBar);
        bar.setVisibility(View.GONE);
    }

    public void registerUser(View view) {

        final String username = editTextUsername.getText().toString();
        final String email = editTextEmail.getText().toString();
        final String password = editTextPassword.getText().toString();
        final String confirmPassword = editTextConfirmPassword.getText().toString();

        if (password.equals(confirmPassword) || confirmPassword.equals(password)) {

            bar.setVisibility(View.VISIBLE);

            StringRequest stringRequest = new StringRequest(Request.Method.POST,
                    Constants.URL_REGISTER,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            bar.setVisibility(View.GONE);

                            try {
                                JSONObject jsonObject = new JSONObject(response);

                                Toast.makeText(getApplicationContext(), jsonObject.getString("message"),
                                        Toast.LENGTH_LONG).show();

                            } catch (JSONException e) {
                                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    bar.setVisibility(View.GONE);
                        Toast.makeText(getApplicationContext(), "Erro: " + error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> params = new HashMap<>();
                    params.put("username", username);
                    params.put("email", email);
                    params.put("password", password);
                    return params;
                }
            };

            RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);

        } else {
            Toast.makeText(getApplicationContext(), "Senhas não conferem, tente novamente", Toast.LENGTH_LONG).show();
        }

    }
}

PostNews(我需要在此處進行一些更改)

public class PostNews extends AppCompatActivity {

    private Button btnpostar;
    private EditText editTextNewsPost, editTextUserFK;
    private ProgressBar bar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_news);

        editTextNewsPost = findViewById(R.id.EditTextNewsPost);
        btnpostar = findViewById(R.id.btnPostar);

    }

    public void salvarNoticia(View view) {

        final String post = editTextNewsPost.getText().toString();

        if (!post.equals("")) {

            bar.setVisibility(View.VISIBLE);

            StringRequest stringRequest = new StringRequest(Request.Method.POST,
                    Constants.URL_REGISTER,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            bar.setVisibility(View.GONE);

                            try {
                                JSONObject jsonObject = new JSONObject(response);

                                Toast.makeText(getApplicationContext(), jsonObject.getString("message"),
                                        Toast.LENGTH_LONG).show();

                            } catch (JSONException e) {
                                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    bar.setVisibility(View.GONE);
                    Toast.makeText(getApplicationContext(), "Erro: " + error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> params = new HashMap<>();
                    return params;
                }
            };

            RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);

        } else {
            Toast.makeText(getApplicationContext(), "Por favor, não poste nada em branco", Toast.LENGTH_LONG).show();
        }

    }
}

共享首選項

public class SharedPrefManager {

    private static SharedPrefManager mInstance;
    private static Context mCtext;

    private static final String SHARED_PREF_NAME = "myname";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_EMAIL = "useremail";
    private static final String KEY_USER_ID = "userid";


    private SharedPrefManager(android.content.Context context){
        mCtext = context;
    }

    public static synchronized SharedPrefManager getInstance(Context context){
        if (mInstance == null) {
            mInstance = new SharedPrefManager(context);
        }
        return mInstance;
    }

    public boolean userLogin(int id, String username, String email){

        SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putInt(KEY_USER_ID, id);
        editor.putString(KEY_USER_EMAIL, email);
        editor.putString(KEY_USERNAME, username);

        editor.apply();

        return true;
    }

    public boolean isLoggedin(){
        SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        if (sharedPreferences.getString(KEY_USERNAME,null) != null){
            return true;
        }
        return false;
    }

    public boolean logout(){
        SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        return true;
    }

    public String getUsername(){
        SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USERNAME, null);
    }

    public String getUserEmail(){
        SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USER_EMAIL, null);
    }
}

如果用戶已經注冊,則可以在此處返回用戶ID:

public function createUser($username, $password, $email){
    if($this->isUserRegistered($username,$email)){
        //return 0; <-- do not return 0
        $userID = ...//get user id from db using $username and $email
        return $userID;
    }else{

如果您操作返回的值,則可以將代碼更改為以下內容,並將userID添加到響應中:

       $result = $db->createUser(   $_POST['username'],
                                $_POST['password'],
                                $_POST['email']
                            );
    if($result == -1){
        $response['error'] = false; 
        $response['message'] = "User registered successfully";
    }elseif($result == -2){
        $response['error'] = true; 
        $response['message'] = "Some error occurred please try again";          
    }elseif($result > 0){
        $response['error'] = true; 
        $response['message'] = "It seems you are already registered, please choose a different email and username"; 
        $response['userID'] = $result;                   
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM