article

Friday, January 7, 2022

AngularJS PHP Mysqli Sign Up with form validation and list records

AngularJS PHP Mysqli Sign Up with form validation and list records

Bootstrap CDN
https://getbootstrap.com/docs/4.3/getting-started/introduction/


angularjs CDN 
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

CREATE TABLE `user` (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com', '86985e105f79b95d6bc918fb45ec7727'),
(2, 'tutorial101.blogspot.com', 'tutorial101@gmail.com', '86985e105f79b95d6bc918fb45ec7727');

ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

ALTER TABLE `user`
  MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
index.php
//index.php
<!DOCTYPE html>
<html ng-app="angularsignup" ng-controller="signup_ctr" ng-init="showdata()">
<head>
<meta charset="UTF-8"> 
<title>AngularJS PHP Mysqli Sign Up with form validation and list records</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body>
<div class="container">
	<center><h1 class="page-header">AngularJS PHP Mysqli Sign Up with form validation and list records</h1></center>
	<div class="row">
		<div class="col-md-4">
			<form ng-submit="myFunc()">
				<h3>Signup Form</h3>
				<hr>
				<div class="form-group">
				    <label for="email">Email</label>
				    <input type="text" class="form-control" id="email" name="email" ng-model="email" placeholder="email@example.com">
				</div>
				<div class="form-group">
				    <label for="username">Username</label>
				    <input type="text" class="form-control" id="username" name="username" ng-model="username">
				</div>
				<div class="form-group">
				    <label for="password">Password</label>
				    <input type="password" class="form-control" id="password" name="password" ng-model="password">
				</div>
				<div class="form-group">
				    <label for="repassword">Re-type Password</label>
				    <input type="password" class="form-control" id="repassword" name="repassword" ng-model="repassword">
				</div>
				<div class="{{alert}}">
					<center>{{alerttext}}</center>
				</div>
				<hr>
				<button type="submit" class="btn btn-success" ng-click="register()"><span class="glyphicon glyphicon-pencil"></span> {{btnName}}</button>
			</form>
		</div>
		<div class="col-md-8">
			<h3>User List</h3>
			<table class="table table-hover table-bordered table-striped">
				<thead>
					<th>Email</th>
					<th>Username</th>
					<th>Password</th>
				</thead>
				<tbody>
					<tr ng-repeat="rs in user">
						<td>{{rs.user_email}}</td>
						<td>{{rs.user_name}}</td>
						<td>{{rs.user_password}}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = angular.module("angularsignup", []);
app.controller("signup_ctr", function($scope, $http, $window) {
    $scope.alert = "alert alert-success";
    $scope.alerttext = "Fill up all the Fields";
    $scope.btnName = "Register";
    var email = $window.document.getElementById('email');
    var username = $window.document.getElementById('username');
    var password = $window.document.getElementById('password');
    var repassword = $window.document.getElementById('repassword');
    email.focus();
    $scope.register = function() {
        if ($scope.email == null){
            $scope.alerttext="Please input email";
            email.focus();
        }
        else if ($scope.username == null) {
            $scope.alerttext="Please input username";
            username.focus();
        } 
        else if ($scope.password == null) {
            $scope.alerttext="Please input password"; 
            password.focus();
        }
        else if($scope.password!=$scope.repassword){
            $scope.alerttext = "Password didn't match";
            repassword.focus();
        } 
        else {
            $scope.btnName = "Checking";
            setTimeout(function() {
				$http({
					method: 'POST',
					url: 'register.php',
					data:{email:$scope.email, username:$scope.username, password:$scope.password}
				}).then(function (data){
					console.log(data)
                    if(data.data==1){
                        $scope.alerttext="Invalid email format";
                        email.focus(); 
                    }
                    else if(data.data==2){
                        $scope.alerttext="Only letters, numbers and underscore allowed";
                        username.focus(); 
                    }
                    else if(data.data==3){
                        $scope.alerttext="Registration Successful";
                        $scope.showdata();
                        $scope.email="";
                        $scope.username="";
                        $scope.password="";
                        $scope.repassword="";
                        email.focus();
                        $scope.btnName = "Register";
                    }
                    else{
                        $scope.alerttext="Registration Failed";
                    }
				},function (error){
					console.log(error, 'can not get data.');
				});
            }, 3000);
        }
    }
    $scope.showdata = function() {
		$http({
            method: 'GET',
            url: 'fetch.php'
        }).then(function (data){
            console.log(data)
			$scope.user = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
    $scope.enter = function(keyEvent) {
        if (keyEvent.which === 13){
            register();
        }
    }
});
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	$output = array();
	$query = $conn->query("select * from user"); 
	if ($query->num_rows > 0) {
	    while ($row = $query->fetch_array()) {
	        $output[] = $row;
	    }
	    echo json_encode($output);
	}
?>
register.php
//register.php
<?php
    include('conn.php');
    $data = json_decode(file_get_contents("php://input"));
    $email = mysqli_real_escape_string($conn, $data->email);
    $username = mysqli_real_escape_string($conn, $data->username);
    $password = mysqli_real_escape_string($conn, $data->password);
    $msg="";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg=1; 
    }
    elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)) {
        $msg=2; 
    }
    else{
        $password=md5($password);
        if ($conn->query("insert into user (user_email, user_name, user_password) values ('$email', '$username', '$password')")) {
            $msg=3;
        } else {
            $msg=4;
        }
    }
    echo json_encode($msg);    
?>

Related Post