Building Hospital Apps Using AngularJS and PHP - #Part 1 - Login System

Creating-First-App-In-AngularJS-With-Basic-File-Setup.png

Image Source

REPOSITORY

https://github.com/angular/angular.js

What Will I Learn?

  • Create connection to MySQL database using PHP PDO
  • Create login system using AngularJS .
  • Using cookies on AngularJs.
  • Send POST data from AngularJS to PHP Script
  • Building the login component.

Requirements

  • Basic HTML, Javascript,CSS
  • Basic AngularJS
  • Basic PHP PDO
  • Knowledge of database administration tools (MySQL and PHPMyAdmin)
  • Localhost (xampp, wampp, or etc)

Difficulty

  • Intermediate

Tutorial Contents

In this tutorial series I will teach you how to create a hospital service application using AngularJS and PHP. In this section I will show you how to make login system for Hospital Application.

Preparation

I will create a folder named hospital_app. Then in the folder I will create a file called index.html

  • Create Database
    The database name for this application is hospital and its table name is users.
  • The structure of users table
NameTypeLength/valueIndeks
usernameVarchar50Primary
passwordVarchar50--
emailVarchar100--

Connect to database

We will connect to the database, for that we need to run our localhost. in this tutorial, I am using Xampp. In the project folder I will create a folder named auth and config.php file to connect to the database.

$hospital_db_host = "localhost";
$hospital_db_user = "root";
$hospital_db_pass = "";
$hospital_db_name = "hospital";

 try
 {
     $DBcon = new PDO("mysql:host={$hospital_db_host};dbname={$hospital_db_name}",$hospital_db_user,$hospital_db_pass);
     $DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 }
 catch(PDOException $e)
 {
     echo "ERROR : ".$e->getMessage();
 }

  • We will connect to the database using the following functions new PDO("mysql:host={$hospital_db_host};dbname={$hospital_db_name}",$hospital_db_user,$hospital_db_pass); this function requires some parameters ie.

a. $hospital_db_host for the database server host address.
b. $hospital_db_name for the database server name.
c. $hospital_db_user for the database server username.
c. $hospital_db_pass for the database server password.

  • This section catch(PDOException $e) will catch if anny error with the database connection function.

Setting Frontend With AngularJS and Bootstrap

  • Load AngularJS
    We have create the index.html file on the preparation section on this tutorial. Now Let's load AngularJS in index.html via CDN:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  • Load AngularJS Cookies
    The login information from the php script will be saved to the frontend in the cookies data. We will need to use AngularJS Cookies to read and save the cookie data, Let's load AngularJS Cookies in index.html via CDN:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-cookies.js"></script>
  • Load Bootstrap
    To create a better view then we will use bootstrap library in this tutorial. Let's load Bootstrap in index.html via CDN:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">

Creating Login Page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hospital App</title>
    
   <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" >
    <style>
        body {
            padding-top: 40px;
            padding-bottom: 40px;
            background-color: #E1F3FC;
        }
        .form-signin {
            max-width: 330px;
            padding: 15px;
            margin: 0 auto;
        }
        .form-signin .form-signin-heading,
        .form-signin .checkbox {
            margin-bottom: 10px;
        }
        .form-signin .checkbox {
            font-weight: normal;
        }
        .form-signin .form-control {
            position: relative;
            height: auto;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            padding: 10px;
            font-size: 16px;
        }
        .form-signin .form-control:focus {
            z-index: 2;
        }
        .form-signin input[type="username"] {
            margin-bottom: -1px;
            border-bottom-right-radius: 0;
            border-bottom-left-radius: 0;
        }
        .form-signin input[type="password"] {
            margin-bottom: 10px;
            border-top-left-radius: 0;
            border-top-right-radius: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <center>
            <img src="icon.png" height="180px" />
        </center>
        <form class="form-signin">
            <center>
                <h2 class="form-signin-heading">Please sign in</h2>
            </center>
            <br/>
            <label for="inputUsername" class="sr-only">Username</label>
            <input type="text" class="form-control" placeholder="Username" required autofocus>
            <label for="inputPassword" class="sr-only">Password</label>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        </form>
    </div>
</body>
</html>
Code Explanation

In the above code I create two input text ie

  • Input username to retrive username from user.
  • Input password to retrive password from user.

Then I added a hospital app logo on the top and a button that will trigger the login function when clicked. The layout will display like this following image.

Screen Shot 2018-06-01 at 15.45.26.png

Implement AngularJS on the Index.html

To connect with AngularJs script Now lets add ng-app and ng-controller on the body tag

<body ng-app="hospitalLogin" ng-controller="hospitalLoginController as hospitalCtrl">

Modify form tag add ng-submit and post method.

  <form class="form-signin" ng-submit="hospitalCtrl.loginForm()" method="POST">

Add ng-model for input text username and password

 <label for="inputUsername" class="sr-only">Username</label>
<input type="username" class="form-control" placeholder="Username" ng-model="hospitalCtrl.username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password"  ng-model="hospitalCtrl.password" required>

The last step is adding depedency injection on span below our sign ini button to show when there is an error happend on our login process.

<span> {{errorMsg}}</span>

AngularJS Script For Authentication

 angular.module('hospitalLogin', ['ngCookies'])
        .controller('hospitalLoginController', ['$scope', '$http', '$cookies', function($scope, $http, $cookies) {
            this.loginForm = function() {
                var dataLogin='username=' +this.loginData.username+'&password='+this.loginData.password;
                $http({
                    method: 'POST',
                    url: 'auth/authentication.php',
                    data: dataLogin,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                })
                .then(function(response) {
            console.log(response);
                    if ( (response.data).trim() === 'correct') {
                        $cookies.put('login_info', this.loginData.username);
                        window.location.href = 'dashboard.html';
                    } else {
                        $scope.errorMsg = "Credential not match";
                    }
                })
            }
        }]);
Code Explanation
  1. We use the hospitalLogin module and the hospitalLoginController we have initialized in the previous html file
  2. When Button Log in Click then loginForm() function will be executed
  3. In the loginForm function we will use $http service which will send data using POST method to server
  4. Then in the response catcher section, we will create a control structure
    when the server sends the 'correct' data response then the user will be directed to the dashboard page and save username into cookies

PHP Authentication Script to check credential info

<?php
require_once 'config.php';
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $DBcon->prepare("SELECT username, password from users WHERE username='".$username."' && password='".$password."'");
$stmt->execute();
$row = $stmt->rowCount();
if ($row > 0){
    echo "correct";
} else{
    echo 'wrong';
}
?>

Code Explanation
  1. line require_once 'config.php'; serves to gain access to the database that we previously created in the file config.php
  2. $username and $passwordworks for receive the variable data from AngularJS http service.
  3. md5($_POST['password']); works for doing md5 encryption to password variable.
  4. $stmt = $DBcon->prepare(); and $stmt->execute(); works for doing query to users database.
  5. $row = $stmt->rowCount(); works to count how much row of query results.
  6. if ($row > 0) server will send response correct to AngularJS $http service.

Creating Dashboard Page

After the login process is successful then the user will be directed to the dashboard page. On the dashboard page we will check whether there are cookies stored in the browser. If cookies do not exist then the user will redirect back to the login page. The code for the dashboard page is like the code block below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hospital App</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" >
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-cookies.js"></script>
</head>
<body ng-app="hospitalApp" ng-controller="DashboardController">
    <h1>Welcome To Dashboard Page</h1>
    <script> 
    var app = angular.module("hospitalApp", ["ngRoute", "ngCookies"]);
    app.controller('DashboardController', ['$scope', '$cookies', '$window', function ($scope, $cookies, $window) {
            // Retrieving a cookie
            var loginCookie = $cookies.get('login_info');
            if (loginCookie) {
                alert("You Have Access To This Page...!!!");
            } else {
                alert("You Don't Have Access To This Page.");
                $window.location.href = 'index.html';
            }
    }]);
    </script>   
</body>
</html>

Code Explanation
  1. On DashboardController declared service $cookies to retrieve cookies data in browser and service $window to move user to another page.
  2. var loginCookie = $cookies.get('login_info'); works for receive the variable from login script.
  3. The If Else control structure works for show allert when the cookies is exist and redirect user to login page when the cookies is not exist.

Conclusion

In this section we have discussed how to create a user authentication system using AngularJS. In the next section we will create a more complex login system for the hospital such as user permissions and dashboard page modifications.

Curriculum

This is My first tutorial About Building Hospital Apps Using AngularJS and PHP

Proof of Work Done

Repository For This Tutorial
https://github.com/iqbalhood/HospitallApp-Part1

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center