article

Saturday, November 13, 2021

AngularJS Login with PHP MySQLi

AngularJS Login with PHP MySQLi

This tutorial used CDN for Bootstrap, Angular JS and Angular Route

CREATE TABLE `tbl_user` (
  `userid` int(11) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `tbl_user` (`userid`, `fullname`, `username`, `email`, `password`) VALUES
(1, 'cairocoder Ednalan', 'cairocoders', '', '123456'),
(2, 'tutorial101', 'tutorial101', '', '123456');

ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `tbl_user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
index.html
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS Login with PHP MySQLi</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
  <h1 class="page-header text-center">AngularJS Login with PHP MySQLi</h1>
  <div ng-view></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="js/angular.js"></script>
<script src="js/controllers/loginCtrl.js"></script>
<script src="js/services/loginService.js"></script>
</body>
</html>
login.html
//login.html
<div class="col-md-4 col-md-offset-4">
    <div class="login-panel panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
            </h3>
        </div>
    	<div class="panel-body">
        	<form role="form" name="logform">
            	<fieldset> sdfsdfsf
                	<div class="form-group">
                    	<input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
                	</div>
                	<div class="form-group">
                    	<input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
                	</div>
                	<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block" ng-disabled="logform.$invalid" ng-click="login(user)"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login</span></button>
            	</fieldset>
        	</form>
    	</div>
    </div>

    <div class="alert alert-danger text-center" ng-show="errorLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ errorMsg }}
    </div>

    <div class="alert alert-success text-center" ng-show="successLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ successMsg }}
    </div>
</div>
angular.js
//angular.js
var app = angular.module('app', ['ngRoute']); //Routing - ngRoute module helps your application to become a Single Page Application.

app.config(function($routeProvider){
	$routeProvider
	.when('/', {
		templateUrl: 'login.html',
		controller: 'loginCtrl'
	})
	.when('/home', {
		templateUrl: 'home.html'
	})
	.otherwise({
		redirectTo: '/'
	});
});
js/services/loginService.js
//js/services/loginService.js
'use strict';

app.factory('loginService', function($http){
	return{
		login: function(user, $scope){
			var validate = $http.post('login.php', user);
			validate.then(function(response){
				if(response.data.error == true){
					$scope.successLogin = false;
					$scope.errorLogin = true;
					$scope.errorMsg = response.data.message;
				}
				else{
					$scope.errorLogin = false;
					$scope.successLogin = true;
					$scope.successMsg = response.data.message;
                    setTimeout(function(){
						window.location.href="http://localhost/devtest/angularjs/angularlogin/#/home";
					},2000);
				}
			});
		}
	}
});
js/controller/loginCtrl.js
//js/controller/loginCtrl.js
'use strict';

app.controller('loginCtrl', function($scope, loginService){
	$scope.errorLogin = false;
	$scope.successLogin = false;

	$scope.login = function(user){
		loginService.login(user, $scope);
	}

	$scope.clearMsg = function(){
		$scope.errorLogin = false;
		$scope.successLogin = false;
	}
});
login.php
//login.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$user = json_decode(file_get_contents('php://input'));

$username = $user->username;
$password = $user->password;

$sql = "SELECT * FROM tbl_user WHERE username='$username' AND password='$password'";
$query = $conn->query($sql);

if($query->num_rows>0){
	$out['message'] = 'Login Successful';
}
else{
	$out['error'] = true;
	$out['message'] = 'Invalid Login';
}

echo json_encode($out);
?>

Related Post