简体   繁体   English

PHP / AndroidStudio-通过获取当前用户作为外键登录进行发布

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

I'm trying to make a news application and I need to register the news and get the id of the current logged in user as a parameter to my PHP file. 我正在尝试制作新闻应用程序,我需要注册新闻并获取当前登录用户的ID作为PHP文件的参数。

I already have the login/logout system and I'm saving it at my Shared Preferences file. 我已经有登录/注销系统,并将其保存在“共享首选项”文件中。

I'm asking because I don't have enough knowledge on how to achieve this with PHP and Android Studio. 我之所以问是因为我没有足够的知识来了解如何使用PHP和Android Studio实现这一目标。

Here are my files, I just need a point in the right direction on what should be the best approach on this matter, even for future references? 这是我的文件,我只需要向正确的方向指出,即使是将来的参考,最好的方法是什么?

Thank you in advance if you are willing to help. 如果您愿意提供帮助,请先谢谢您。

Constants 常数

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";
}

DBOperations 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 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(Don't know how to change this) 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);

SignUp (for reference, working) 注册(供参考,正在运行)

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 (I need to do some changes here) 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();
        }

    }
}

SharedPreferences 共享首选项

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);
    }
}

In case user is already registered, you can return user id here: 如果用户已经注册,则可以在此处返回用户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{

If you manipulate returned values, you can change your code to something like this and add userID to your response: 如果您操作返回的值,则可以将代码更改为以下内容,并将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