PHP / AndroidStudio - 通过将当前用户作为外键登录来发布帖子

时间:2018-03-13 14:27:07

标签: php android mysql android-volley

我正在尝试制作新闻应用,我需要注册新闻,并将当前登录用户的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";
}

DBOperations

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

SignUp(供参考,工作)

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

    }
}

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

1 个答案:

答案 0 :(得分:0)

如果用户已注册,您可以在此处返回用户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;                   
    }