Thursday 27 October 2016

Login & Register Page With php mysql

Create Table 

      register.sql

"CREATE TABLE register ( ".
       "id INT(20) AUTO_INCREMENT, ".
       "name VARCHAR(50), ".
       "username VARCHAR(70), ".
       "password VARCHAR(35), ".
       "email VARCHAR(40), ". 
       "PRIMARY KEY ( id )); ";


PHP Files

 db_Connect.php

   <?php

 define('HOST',’Your hostname');
 define('USER',user name);
 define('PASS','**********');
 define('DB',db_name');
 
 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
 ?>

register.php

<?php

 $name = $_GET['name'];
 $username = $_GET['username'];
 $password = $_GET['password'];
 $email = $_GET['email'];

 if($name == '' || $username == '' || $password == '' || $email == ''){
 echo 'please fill all values';
 }else{
 require_once('db_Connect.php');
 $sql = "SELECT * FROM register WHERE username='$username' OR email='$email'";

 $check = mysqli_fetch_array(mysqli_query($con,$sql));

 if(isset($check)){
 echo 'username or email already exist';
 }else{
 $sql = "INSERT INTO register (name,username,password,email) VALUES('$name','$username','$password','$email')";
 if(mysqli_query($con,$sql)){
 echo 'successfully registered';
 }else{
 echo 'oops! Please try again!';
 }
 }
 mysqli_close($con);
 }
?>

login.php

<?php
            if($_SERVER['REQUEST_METHOD']=='POST'){
                        $username = $_POST['username'];
                        $password = $_POST['password'];
                        require_once('db_Connect.php');
                        $sql = "select * from register where username='$username' and  password='$password'";
                        $check = mysqli_fetch_array(mysqli_query($con,$sql));
                        if(isset($check)){
                                    echo "success";
                        }else{
                                    echo "Invalid Username or Password";
                        }
            }else{
                        echo "error try again";
            }
?>

Android Files

AndroidManifest.xml 

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.jainish.loginregistration">

    <uses-permission android:name="android.permission.INTERNET" />

    <application   
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher" 
        android:label="@string/app_name" 
        android:supportsRtl="true" 
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity" 
                  android:label="Login Page">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".UserProfile" 
                  android:label="UserProfile">
        </activity>
        <activity android:name=".RegisterActivity" 
                  android:label="Register Page">
        </activity>
    </application>
</manifest>

build.gradle.xml

 compile 'com.squareup.picasso:picasso:2.4.0'
 compile 'com.loopj.android:android-async-http:1.4.5'
 compile files("${android.getSdkDirectory().getAbsolutePath()}" +
     File.separator + "platforms" + File.separator + "android-23" +
     File.separator + "optional" + File.separator + "org.apache.http.legacy.jar")

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    tools:context="com.jainish.loginregistration.LoginActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linear1"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="User Name"
        android:id="@+id/textView" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_name"
        android:inputType="text"/>
</LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear2"
        android:layout_below="@+id/linear1"
        android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:id="@+id/textView2" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/et_password" />

</LinearLayout>
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/btn_login"
        android:layout_below="@+id/linear2"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:gravity="center"
        android:text="No account yet? Create one"
        android:id="@+id/click_register"
        android:layout_below="@id/btn_login"
        android:layout_marginTop="15dp"/>
    </RelativeLayout>

</ScrollView>

LoginActivity.class

package com.jainish.loginregistration;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends AppCompatActivity {

   
private EditText et_name,et_password;
   
private Button btn_login;
    String
username;
    String
password;
   
public static final String USER_NAME = "USERNAME";
    TextView
click_register;

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

       
et_name = (EditText)findViewById(R.id.et_name);
       
et_password = (EditText)findViewById(R.id.et_password);

       
click_register = (TextView)findViewById(R.id.click_register);
       
click_register.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View view) {
                Intent intent =
new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });

       
btn_login = (Button)findViewById(R.id.btn_login);
       
btn_login.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View view) {
               
username = et_name.getText().toString();
               
password = et_password.getText().toString();
                login(
username,password);
            }
        });
    }
   
private void login(final String username, String password) {
       
class LoginAsync extends AsyncTask<String, Void, String> {
           
private Dialog loadingDialog;

           
@Override
           
protected void onPreExecute() {
               
super.onPreExecute();
               
loadingDialog = ProgressDialog.show(LoginActivity.this, "Please wait",                                         "Loading...");
            }

           
@Override
           
protected String doInBackground(String... params) {
                String uname = params[
0];
                String pass = params[
1];

                InputStream is =
null;
                List<NameValuePair> nameValuePairs =
new ArrayList<NameValuePair>();
                nameValuePairs.add(
new BasicNameValuePair("username", uname));
                nameValuePairs.add(
new BasicNameValuePair("password", pass));
                String result =
null;

               
try{
                    HttpClient httpClient =
new DefaultHttpClient();
                    HttpPost httpPost =
new HttpPost(
                           
"http://energykrish.16mb.com/login.php");
                    httpPost.setEntity(
new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    BufferedReader reader =
new BufferedReader(new InputStreamReader(is,                                                "UTF-8"), 8);
                    StringBuilder sb =
new StringBuilder();
                    String line =
null;
                   
while ((line = reader.readLine()) != null)
                    {
                        sb.append(line +
"\n");
                    }
                    result = sb.toString();
                }
catch (ClientProtocolException e) {
                    e.printStackTrace();
                }
catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
catch (IOException e) {
                    e.printStackTrace();
                }
               
return result;
            }

           
@Override
           
protected void onPostExecute(String result){
                String s = result.trim();
               
loadingDialog.dismiss();
                
if(s.equalsIgnoreCase("success")){
                    Intent intent =
new Intent(LoginActivity.this, UserProfile.class);
                    intent.putExtra(
USER_NAME, username);
                    finish();
                    startActivity(intent);
                }
else {
                    Toast.makeText(getApplicationContext(),
"Invalid User Name or Password",                              Toast.LENGTH_LONG).show();
                }
            }
        }
        LoginAsync la =
new LoginAsync();
        la.execute(username, password);
    }
}

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_register"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    tools:context="com.jainish.loginregistration.RegisterActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear1"
        android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Name" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_name" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear2"
        android:orientation="vertical"
        android:layout_below="@+id/linear1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Username" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_username" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear3"
        android:orientation="vertical"
        android:layout_below="@+id/linear2">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Password" />
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:id="@+id/et_password" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear4"
        android:orientation="vertical"
        android:layout_below="@+id/linear3">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Re-Enter Password" />
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:id="@+id/et_re_password" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linear5"
        android:orientation="vertical"
        android:layout_below="@+id/linear4">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Email" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:id="@+id/et_email" />
</LinearLayout>
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/btn_register"
        android:layout_below="@+id/linear5"
        android:layout_marginTop="10dp"/>
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:id="@+id/btn_back"
        android:layout_below="@+id/btn_register"
        android:layout_marginTop="10dp"/>
    </RelativeLayout>

</ScrollView>

RegisterActivity.class

package com.jainish.loginregistration;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends AppCompatActivity {

    private EditText et_name,et_username,et_password,et_re_password,et_email;
    private Button btn_register,back;
    private static final String REGISTER_URL = "http://energykrish.16mb.com/register.php";

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

        et_name = (EditText) findViewById(R.id.et_name);
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        et_re_password = (EditText) findViewById(R.id.et_re_password);
        et_email = (EditText) findViewById(R.id.et_email);
        btn_register = (Button) findViewById(R.id.btn_register);

        back = (Button)findViewById(R.id.btn_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                startActivity(intent);  
            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                        String name = et_name.getText().toString();
                        String username = et_username.getText().toString();
                        String password=et_password.getText().toString();
                        String email = et_email.getText().toString();
                        String confirmpassword = et_re_password.getText().toString();

                        if ((et_name.getText().toString().trim().length() == 0)) {
                            Toast.makeText(getApplicationContext(), "Please enter your name", 
                                 Toast.LENGTH_SHORT).show();
                        }
                        else if ((et_username.getText().toString().trim().length() == 0)) {
                            Toast.makeText(getApplicationContext(), "Please enter your Username", 
                                 Toast.LENGTH_SHORT).show();
                        }
                        else if (et_email.getText().toString().trim().length() == 0)
                        {
                            Toast.makeText(getApplicationContext(), "Please enter your Email ID",
                                 Toast.LENGTH_LONG).show();
                        }
                        else if ((!isValidEmail(email))) {
                            Toast.makeText(getApplicationContext(), "Please enter valid Email ID",
                                 Toast.LENGTH_LONG).show();
                        }
                        else if ((et_password.getText().toString().trim().length() <= 6)) {
                            if(et_password.getText().toString().trim().length() <= 0)
                            {
                                Toast.makeText(getApplicationContext(), "Please enter your Password",
                                     Toast.LENGTH_LONG).show();
                            }
                            else {
                                Toast.makeText(getApplicationContext(), "Please enter more then 6 character",
                                     Toast.LENGTH_LONG).show();
                            }
                        }
                        else if ((et_re_password.getText().toString().trim().length() <= 6)) {
                            if(et_password.getText().toString().trim().length() <= 0){
                                Toast.makeText(getApplicationContext(), "Please re-enter your Password",
                                     Toast.LENGTH_LONG).show();                    }
                            else {
                                Toast.makeText(getApplicationContext(), "Please enter more then 6 character",
                                     Toast.LENGTH_LONG).show();
                            }
                        }
                        else if (!password.equals(confirmpassword)) {
                            Toast.makeText(getApplicationContext(), "Password Does Not Matches",
                                 Toast.LENGTH_LONG).show();
                        }
                        else if (view == btn_register) {
                            registerUser();
                        }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void registerUser() {
        String name = et_name.getText().toString().trim();
        String username = et_username.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        String email = et_email.getText().toString().trim();
        register(name,username,password,email);
    }
    private void register(String name, String username, String password, String email) {
        String urlSuffix = "?name="+name+"&username="+username+"&password="
                           +password+"&email="+email;
        class RegisterUser extends AsyncTask<String, Void, String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(RegisterActivity.this, "Please Wait",null, true, true);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }
            @Override
            protected String doInBackground(String... params) {
                String s = params[0];
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(REGISTER_URL+s);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String result;
                    result = bufferedReader.readLine();
                    return result;
                }catch(Exception e){
                    return null;
                }
            }
        }
        RegisterUser ru = new RegisterUser();
        ru.execute(urlSuffix);
    }
    private boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

activity_user_profile.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_profile"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.jainish.loginregistration.UserProfile">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:id="@+id/textView3"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

UserProfile.class

package com.jainish.loginregistration;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class UserProfile extends AppCompatActivity {
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);

        Intent intent = getIntent();
        String username = intent.getStringExtra(LoginActivity.USER_NAME);

        TextView textView = (TextView) findViewById(R.id.textView3);

        textView.setText("Welcome : "+username);

    }
}

Output :