Friday, July 14, 2017

Login & registration system using PHP, MySQL & Retrofit 2 library

I am going to create user login & registration system. I'll use PHP in backend & MySQL database. JSON response will be handled using retrofit 2 library. Let's start.

First, lets create a database. First, create a database. I have named it as "jnklogreg". Then create a table with 4 column - id, Name, Email, Password. Here, the table name is "consumers". Below is the structure of the table :


Now our database is ready. Next come to server side coding. Create a file "init.php". It contains the configuration of our database. Here is it's contents :

<?php

$host = "localhost";
$user = "root";
$password = "";
$database = "jnklogreg";

$conn = mysqli_connect($host, $user, $password, $database);

?>

Here mysqli_connect function creates connection with the database. Put your password in the $password field. Next create another php file - "register.php". Below is it's contents :

<?php 
require 'init.php';

$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];

// variables for handling response
$code = "";
$message = "";
$response = array();

//checking the email already registered or not
$sql = "SELECT * FROM consumers WHERE email LIKE '".$email."';";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $code = 0;
    $message = "user already registered with this email";
    
    print_r(error_get_last());
} else {
    $sql_insert = "INSERT INTO consumers(Name, Email, Password) VALUES('$name', '$email', '$password')";
    $result_of_insertion = mysqli_query($conn, $sql_insert);
    
    if ($result_of_insertion) {
        $code = 1;
        $message = "Registration successful!";
    } else {
        $code = 0;
        $message = "Error!!!";
        
        print_r(error_get_last());
    }
}

$response['code'] = $code;
$response['message'] = $message;

echo json_encode($response);

?>

Here first we imported the init.php file so that we can use it's $conn variable which holds the connection with database. $name , $email & $password contains the corresponding values which will be assigned using POST method. Then we checked whether the email is already registered or not. If yes, mysqli_num_rows() function will return rows, in other words - the email is alredy registered. Otherwise data gonna be inserted in table. Finally we encoded the response in JSON.

Next, another php file login.php to handle login system. Contents below :

<?php
require 'init.php';

$email = $_POST["email"];
$password = $_POST["password"];

$code = "";
$message = "";
$user = "";
$response = array();

$sql_email = "SELECT * FROM consumers WHERE Email LIKE '$email';";

$result_email = mysqli_query($conn, $sql_email);

if (mysqli_num_rows($result_email) > 0) {
    $sql_password = "SELECT * FROM consumers WHERE Email LIKE '$email' AND Password LIKE '$password';";
    $result_password = mysqli_query($conn, $sql_password);
    if (mysqli_num_rows($result_password) > 0) {
        // getting value from 'Name' column 
        $row = mysqli_fetch_row($result_password);
        $user = $row[1];
        $code = 1;
        $message = "Login successful!";
    } else {
        $user = "unavailable";
        $code = 0;
        $message = "Wrong password";
    }
} else {
    $user = "unavailable";
    $code = 0;
    $message = "Wrong email";
    print_r(error_get_last());
}

$response['code'] = $code;
$response['message'] = $message;
$response['user'] = $user;

echo json_encode($response);

?>

First we have imported init.php file to access the database connection. Then values assigned in $email & $password variable using POST method. First we checked whether the email is correct or not. If correct , then we fetched associated rows using both email & password. Other things are pretty simple. Finally we encoded the code, message & user name in JSON format.

So far, our backend is ready. Now come to the android part...

As usual, first create a project in Android Studio. Add permission for accessing internet. Open AndroidManifest.xml & add the followings :

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Now add dependency for using retrofit.Open build.gradle file & add the following :

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

Now sync the project & make sure that there is no error. Now create a model class . In our JSON response , there were 3 fields - code, message & user. I have designed this model class keeping in mind the JSON response. Create ResponseModel.java class . Contents are as follows :

public class ResponseModel {

    @SerializedName("code")
    private String code;
    @SerializedName("message")
    private String message;
    @SerializedName("user")
    private String user;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}

Here @Serialized annotaion is needed to map the JSON keys with our fields. In keeping with camelCase naming convention, using underscore is not recommended.
@SerializedName("code") means our JSON key "code" should be mapped to the java field "code". If both the values are same, there would be no need of @Serialized annotation.

Next create ApiClient.java class. Retrrofit object will be initialized here.

public class ApiClient {

    private static final String BASE_URL = "ipaddress/directory/";
    private static Retrofit retrofit  = null;

    public static Retrofit getClient () {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }

}

in the BASE_URL, put ip address and directory. Next, create an interface "ApiInterface.class". Here we gonna put the endpoints.

public interface ApiInterface {

    @FormUrlEncoded
    @POST("register.php")
    Call<ResponseModel> registerUser(@Field("name") String name, @Field("email") String email, @Field("password") String password);

    @FormUrlEncoded
    @POST("login.php")
    Call<ResponseModel> loginUser(@Field("email") String email, @Field("password") String password);

}

Here we have created two separate methods for registration & login purpose. Now create "Registeractivity.java". There we have theree edittext for inputting name,email & password. There is  a button to save these. Here is the full content :

public class RegisterActivity extends AppCompatActivity {

    EditText nameEditText, emailEditText, passwordEditText;
    Button registerButton;
    String name, email, password;
    ProgressDialog progressDialog;


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

        registerButton = (Button) findViewById(R.id.btnRegister);
        nameEditText = (EditText) findViewById(R.id.etRegName);
        emailEditText = (EditText) findViewById(R.id.etRegEmail);
        passwordEditText = (EditText) findViewById(R.id.etRegPassword);

        progressDialog = new ProgressDialog(this);
    }

    public void onRegisterUser(View view) {

        progressDialog.setMessage("Submitting. Please wait...");
        progressDialog.show();

        name = nameEditText.getText().toString();
        email = emailEditText.getText().toString();
        password = passwordEditText.getText().toString();

        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
        Call<responsemodel> call = apiInterface.registerUser(name, email, password);
        call.enqueue(new Callback<responsemodel>() {
            @Override
            public void onResponse(Call<responsemodel> call, Response<responsemodel> response) {
                progressDialog.dismiss();
                if (response.body().getCode().equals("1")) {
                    Toast.makeText(RegisterActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RegisterActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<responsemodel> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(RegisterActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}</responsemodel></responsemodel></responsemodel></responsemodel></responsemodel>

We've called registerUser method & passed the name, email & password. The Json response is handled inside onResponse() & onFailure() method. The response are shown in a toast message. The xml file of this activity is given below :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nooo.RegisterActivity"
    android:background="#3C3F41">

    <EditText
        android:maxLines="1"
        android:inputType="textCapWords"
        android:background="#2b2b2b"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:textColor="#FFFFFF"
        android:hint="Your Name"
        android:id="@+id/etRegName"/>

    <EditText
        android:maxLines="1"
        android:inputType="textCapWords"
        android:background="#2b2b2b"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:layout_below="@+id/etRegName"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:textColor="#FFFFFF"
        android:hint="Your Email"
        android:id="@+id/etRegEmail"/>

    <EditText
        android:maxLines="1"
        android:background="#2b2b2b"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:layout_below="@+id/etRegEmail"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:textColor="#FFFFFF"
        android:hint="Enter Password"
        android:id="@+id/etRegPassword"
        android:inputType="textPassword"/>

    <Button
        android:layout_below="@+id/etRegPassword"
        android:layout_margin="10dp"
        android:id="@+id/btnRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Register"
        android:background="#FF0071"
        android:onClick="onRegisterUser"/>




</RelativeLayout>

In the main activity , the login operation is handled. Here is the xml file :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3C3F41"
    tools:context="com.example.nooo.MainActivity">

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="10dp"
        android:background="#2B2B2B"
        android:hint="Enter your email"
        android:inputType="textCapWords"
        android:maxLines="1"
        android:padding="10dp"
        android:textColor="#FFFFFF" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignStart="@+id/etEmail"
        android:layout_below="@+id/etEmail"
        android:layout_margin="10dp"
        android:background="#2b2b2b"
        android:hint="Enter Your Password"
        android:inputType="textPassword"
        android:maxLines="1"
        android:padding="10dp"
        android:textColor="#FFFFFF" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPassword"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:background="#FF0071"
        android:onClick="onLogin"
        android:text="Log In" />

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnLogin"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:onClick="openRegisterActivity"
            android:text="Not member yet? Register Now"
            android:textColor="#FFFFFF"
            android:textSize="18dp" />

    </LinearLayout>

</RelativeLayout>

The java part is almost same as the RegisterActivity.java, we called interface method loginUser & passed emial & password. Success response is handled inside onResponse() method. If login success, there'll be a message like "Login successs!Welcome userName". This is shown as toast message inside onResponse() method. Full code is given below :

public class MainActivity extends AppCompatActivity {

    EditText emailEditText, passwordEditText;
    Button loginButton;
    String email, password;
    ProgressDialog progressDialog;

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

        emailEditText = (EditText) findViewById(R.id.etEmail);
        passwordEditText = (EditText) findViewById(R.id.etPassword);
        loginButton = (Button) findViewById(R.id.btnLogin);
        progressDialog = new ProgressDialog(this);

    }

    public void onLogin(View view) {
        progressDialog.setMessage("Submitting. Please wait...");
        progressDialog.show();
        email = emailEditText.getText().toString();
        password = passwordEditText.getText().toString();

        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
        Call<ResponseModel> call = apiInterface.loginUser(email, password);
        call.enqueue(new Callback<ResponseModel>() {
            @Override
            public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
                progressDialog.dismiss();
                if (response.body().getCode().equals("1")) {
                    Toast.makeText(MainActivity.this, response.body().getMessage() + "Welcome " + response.body().getUser(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseModel> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void openRegisterActivity(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

}

Thats all! Now time to run & check.

0 comments:

Post a Comment