简体   繁体   English

获取注册用户的信息

[英]Getting information of registered users

I have two php scripts. 我有两个PHP脚本。 The first one deals with the registration a user through an android app. 第一个通过Android应用程序处理用户的注册。 Here it is: 这里是:

<?php

session_start();
require "init.php";
header('Content-type: application/json');
$id = $_POST['id'];
$email = $_POST['email'];
$user_name = $_POST['user_name'];

$user_pass = $_POST['user_pass'];
$passwordEncrypted = sha1($user_pass);

$confirmPass = $_POST['confirm_pass'];
$confPasswordEncrypted = sha1($confirmPass);

$msg = "Congratulations. You are now registered to the most amazing app ever!";

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    $don = array('result' => "fail", "message" => "Please enter a valid email");
}
if ($email && $user_name && $user_pass && $confirmPass && filter_var($email, FILTER_VALIDATE_EMAIL)) {

    $sql_query = "select * from user_info WHERE email  ='" . mysqli_real_escape_string($con, $email) . "' or user_name 
        ='" . mysqli_real_escape_string($con, $user_name) . "'";

    $result = mysqli_query($con, $sql_query);

    $results = mysqli_num_rows($result);

    if ($results) {
        $don = array('result' => "fail", "message" => "Email or username exists.");
    } else {

        $sql_query = "insert into user_info values('$id','$email','$user_name','$passwordEncrypted','$confPasswordEncrypted');";

        if (mysqli_query($con, $sql_query)) {

            $_SESSION['id'] = mysqli_insert_id($con);
            $id = mysqli_insert_id($con);

            $don = array('result' => "success", "message" => $id);
            mail($email, "Well done. You are registered to my sample app!", $msg);
        }
    }
} else if (!$email) {
    $don = array('result' => "fail", "message" => "Please enter a valid email");
} else if (!$user_name) {

    $don = array('result' => "fail", "message" => "Please enter your username");
} else if (!$user_pass) {

    $don = array('result' => "fail", "message" => "Please enter a password");
} else if (!confirmPass) {

    $don = array('result' => "fail", "message" => "Please confirm your password");
}
echo json_encode($don);
?>

After the successful registration,the user gets a Toast message in his android phone,showing his id. 成功注册后,用户会在其Android手机中收到一条Toast消息,并显示其ID。 I will change this later to a message saying something like successful registration..Now I have another php script that gets the user information. 稍后,我将其更改为一条消息,提示注册成功。.现在,我还有另一个可获取用户信息的php脚本。

<?php
include("init.php");

$get_posts = "SELECT * FROM user_info where id='" . $_SESSION['id'] . "' LIMIT 1";
error_reporting(E_ALL);
ini_set("display_errors", 1);
$run_posts = mysqli_query($con, $get_posts);

$posts_array = array();

while ($posts_row = mysqli_fetch_array($run_posts)) {

    $row_array['id'] = $posts_row['id'];
    $row_array['user_name'] = $posts_row['user_name'];

    array_push($posts_array, $row_array);
}
$string = json_encode($posts_array, JSON_UNESCAPED_UNICODE);

echo $string;
?>

However that script returns an empty array. 但是,该脚本返回一个空数组。 Please note that I already have one user registered and his detailed are shown in the user_info table. 请注意,我已经注册了一个用户,其详细信息显示在user_info表中。

[]

Why is this happening? 为什么会这样呢?

Edit . 编辑

The is my Android register code. 这是我的Android注册代码。

public class RegisterFragment extends Fragment {
private SessionManager session;
EditText etEmail, etUsername, etPassword,etConfirmPassword;
String email, userName, userPass,confirmPassword;
Button registerButton;
SqliteHandler sql;
public RegisterFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_register, container, false);
    Toolbar myToolbar = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
    setHasOptionsMenu(true);

    etEmail = (EditText)v.findViewById(R.id.name);
    etUsername = (EditText)v.findViewById(R.id.user_name);
    etPassword = (EditText)v.findViewById(R.id.user_pass);
    etConfirmPassword = (EditText)v.findViewById(R.id.confirm_pass);
    registerButton = (Button)v.findViewById(R.id.registerBtn);

    session = new SessionManager(getActivity());

    if (session.isLoggedIn()) {
        // User ites already logged in. Take him to main activity
        Intent intent = new Intent(getActivity(), Welcome.class);
        startActivity(intent);

    }
    registerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = etEmail.getText().toString();
            userName = etUsername.getText().toString();
            userPass = etPassword.getText().toString();
            confirmPassword = etConfirmPassword.getText().toString();

            if(userPass.equals(confirmPassword)){

                registerUser(email, userName, userPass, confirmPassword);

            }else{

                Toast.makeText(getActivity(),"Passwords don't match",Toast.LENGTH_SHORT).show();
            }
        }
    });

    return v;
}
private void registerUser(final String email, final String userName,
                          final String password,final String confirmPassword) {

    String tag_string_req = "req_register";

    StringRequest strReq = new StringRequest(Request.Method.POST,
            Config.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d("Response", "Register Response: " + response.toString());

            try {
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.getString("result").equals("success")) {

                    //Toast.makeText(getActivity(),jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                    String id = jsonObject.getString("message");
                    Log.d("Theo", id);
                    //$don = array('result' =>"success","message"=>mysqli_insert_id($con));

                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("id", String.valueOf(id));
                    editor.putString("email", email);
                    editor.putString("user_name", userName);
                    editor.putString("user_pass", password);
                    editor.putString("confirm_pass", confirmPassword);

                    editor.commit();
                }
                else if (jsonObject.getString("result").equals("fail")) {
                    Toast.makeText(getActivity(),jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                }
            }catch(JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", "Registration Error: " + error.getMessage());
            Toast.makeText(getActivity(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", "");
            params.put("email", email);
            params.put("user_name", userName);
            params.put("user_pass", password);
            params.put("confirm_pass", confirmPassword);
            return params;
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
   }
}

As you've mentioned you're accessing this script from Android phone. 如前所述,您正在从Android手机访问此脚本。 In that case you can't use sessions , as they won't get shared. 在这种情况下,您将无法使用session ,因为它们不会被共享。

What you need to do is send a userid along with second request to get the User information and change the SQL query to something like this, 您需要做的是发送用户ID和第二个请求,以获取用户信息并将SQL查询更改为类似的内容,

$get_posts = "SELECT * FROM user_info where id='".$_GET['id']."' LIMIT 1";

Assuming you will send data in parameters. 假设您将通过参数发送数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM