简体   繁体   中英

I am developing an android app for job search .here i am using PHP as back end

in php code when we register automatically create a random code as user id. in android app when we save profile information i cant the user id will different. so how to manage user id in all activities and fragment keep same user id until logout help me............................................... **

Sign up code:

<?php
 session_start();

   if($_SERVER['REQUEST_METHOD']=='POST'){

       include_once("db_connect.php");


    $username = $_POST['user_name'];
    $useremail = $_POST['user_email'];
    $usermobile = $_POST['user_mobile'];
    $password = $_POST['password'];



 function randomstring($len) {
    $string = "";
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    for($i=0;$i<$len;$i++)
        $string.=substr($chars,rand(0,strlen($chars)),1);
    return $string;
    }
    $rndm_code=randomstring(5);




$CheckSQL = "SELECT * FROM user WHERE user_email='$useremail'";
    $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));

          if(isset($check)){

         echo 'Email Already Exist';

          }

 else{


  $Sql_Query = "insert into user (user_id,user_name,user_email,user_mobile,password) values ('$rndm_code','$username','$useremail','$usermobile','$password')";


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



  echo 'User Registration Successfully';

 }
 else
 {

 echo 'Try Again';
 }

 }
 }
 mysqli_close($con);

 ?>

Android code:

 private void registerUser() {
             isConnectingToInternet();
            final String username = signupname.getText().toString().trim();
            final String email = signupemail.getText().toString().trim();
            final String phone = signupphone.getText().toString().trim();
            final String password = signuppassword.getText().toString().trim();


            pDialog = new ProgressDialog(SignupActivity.this);
            pDialog.setMessage("Signing Up.. Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();


            StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_REGISTER,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String ServerResponse) {

                            // Hiding the progress dialog after all task complete.
                            pDialog.dismiss();

                            // Showing response message coming from server.
                            Toast.makeText(SignupActivity.this, ServerResponse, Toast.LENGTH_LONG).show();


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

                            // Hiding the progress dialog after all task complete.
                            pDialog.dismiss();

                            // Showing error message if something goes wrong.
                            Toast.makeText(SignupActivity.this,"Check Internet connection", Toast.LENGTH_LONG).show();
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() {

                    // Creating Map String Params.
                    Map<String, String> params = new HashMap<String, String>();

                    // Adding All values to Params.
                    params.put("user_name",username);
                    params.put("user_email",email);
                    params.put("user_mobile", phone);
                    params.put("password",password);

                    return params;
                }

            };


            RequestQueue requestQueue = Volley.newRequestQueue(SignupActivity.this);


            requestQueue.add(stringRequest);




        }**

Your server response needs to contain the id in addition to the response text. Usually, this is done by formatting the response as JSON.

Instead of just "User Registration Successfully", the response from the PHP script could be

{
  "message":"User Registration Successfully",
  "userId":<your_user_id_goes_here>
}

You can use json_encode in PHP to create this format for you from an array. The code for that would look something like this

echo json_encode([
   "message" => "User Registration Successfully",
   "userId" => $rndm_code
]);
exit();

It would be good to exit after sending the response so that your JSON deos not becoem invalid by you accidentally echoing something more somewhere later.

In the android app, you would then get the data from the JSON - I am not experienced in android, but I think you would do this by making it a JsonObjectRequest instead of a StringRequest, and then displaying serverResponse.getString("message") and saving serverResponse.getString("userId") as the id in a variable somewhere.

<?php
 session_start();

   if($_SERVER['REQUEST_METHOD']=='POST'){

       include_once("db_connect.php");


    $username = $_POST['user_name'];
    $useremail = $_POST['user_email'];
    $usermobile = $_POST['user_mobile'];
    $password = $_POST['password'];



 function randomstring($len) {
    $string = "";
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    for($i=0;$i<$len;$i++)
        $string.=substr($chars,rand(0,strlen($chars)),1);
    return $string;
    }
    $rndm_code=randomstring(5);




$checkUser = "SELECT * FROM user WHERE user_email='$useremail' OR user_mobile='$usermobile'";

 $userStatus = mysqli_fetch_array(mysqli_query($con,$checkUser));

 if(isset($userStatus)){
 die(json_encode(array("success"=>0,"message"=>"Email or Mobile no already exist!!")));
 }
 else
 {

$sql =$con->prepare( "INSERT INTO user(user_id,user_name,user_email,user_mobile,password) VALUES ('$rndm_code','$username', '$useremail', '$usermobile','$password')");
$sql->bind_param("ssss",$rndm_code, $username, $useremail, $usermobile,$password);

if($sql->execute())
{
echo(json_encode(array("success"=>1,"message"=>"Account created successfully!! Please Login")));
}
else
{
die("Something Error".$sql."<br>".mysqli_error($con));
}

 }

}else{

  die(json_encode(array("success"=>0,"message"=>"Empty Request Parameters..!!")));

}
mysqli_close($con);

 ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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