article

Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Tuesday, January 18, 2022

AngularJS Multiple Upload with Progress Bar and PHP MySQLi

AngularJS Multiple Upload with Progress Bar and PHP MySQLi

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/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
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS Upload with Progress Bar and PHP MySQLi</title>
<meta charset="utf-8">
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="progressbarupload" ng-controller="MainControl" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Multiple Upload with Progress Bar and PHP MySQLi</h1>
	<div class="row">
		<div class="col-md-12">
			<h3 class="text-left">Upload File/s</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files" multiple>
			<hr>
			<button class="btn btn-primary" ng-click="upload()"><span class="glyphicon glyphicon-download-alt"></span> Upload</button>
			
			<progress id="progress" max="100" value="{{progressBar}}" ng-show="showProgress" style="height:30px; width:100%; margin-top:30px;"></progress>
			<div class="text-center">{{progressCounter}}</div>
			
			<div ng-show="error" class="alert alert-danger text-center" style="margin-top:30px;">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-remove"></span> {{ errorMessage }}
			</div>
			<div ng-show="success" class="alert alert-success text-center" style="margin-top:30px;">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
			</div>
			
		</div>
	</div>	
	<div class="row">
		<div class="col-md-12">
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
					<th>File</th>
				</thead>
				<tbody>
					<tr ng-repeat="upload in uploads">
						<td>{{ upload.file_name }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
//script.js
var app = angular.module('progressbarupload', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
		restrict: 'A',
		link: function($scope, elm, attrs){
			elm.bind('change', function(){
				$parse(attrs.fileInput).assign($scope, elm[0].files);
				$scope.$apply();
			});
		}
	}
}]);
app.controller('MainControl', function($scope, $http){
	$scope.showProgress = false;
	$scope.error = false;
	$scope.errorMessage = "";
	$scope.success = false;
	$scope.successMessage = "";
	$scope.upload = function(){
		
		$http({
            method: 'POST',
            url: 'upload.php',
			transformRequest: function (data) { 
				var uploadForm = new FormData();
				angular.forEach($scope.files, function(file){
					uploadForm.append('file[]', file);
				});
				return uploadForm; 
            },
			headers: {'Content-Type':undefined, 'Process-Data': false},
			uploadEventHandlers: {
		        progress: function (e) {
		                  if (e.lengthComputable) {
		                  		$scope.showProgress = true;
		                     	$scope.progressBar = (e.loaded / e.total) * 100;
		                     	$scope.progressCounter = $scope.progressBar.toFixed(2) + ' %';
		                  }
		        }
		    }
        }).then(function (data){
            console.log(data)
			if(data.error){
				$scope.error = true;
				$scope.errorMessage = data.data.message;
			}
			else{
				$scope.success = true;
				$scope.successMessage = data.data.message;
				$scope.fetch();
			}
        },function (error){
            console.log(error, 'can not get data.');
        });
		
		
	}

	$scope.fetch = function(){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.uploads = data.data;      
        },function (error){
            console.log(error, 'can not get data.');
        });
	}

	$scope.clearMessage = function(){
		$scope.error = false;
		$scope.errorMessage = "";
		$scope.success = false;
		$scope.successMessage = "";
	}	
});
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	$output = array();
	$sql = "SELECT * FROM uploads";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
upload.php
//upload.php
<?php

	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	$out = array('error' => false);

	if(!empty($_FILES['file']['name'])){
		$count = count($_FILES['file']['name']);
		foreach ($_FILES['file']['name'] as $key => $filename){
			$newFilename = time() . "_" . $filename;

			$path = 'upload/' . $newFilename;

			if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $path)){
				$sql = "INSERT INTO uploads (file_name) VALUES ('$newFilename')";
				$query=$conn->query($sql);
			}
			 	
			if($query){
				if($count > 1){
					$out['message'] = 'Files Uploaded Successfully';
				}
				else{
					$out['message'] = 'File Uploaded Successfully';
				}
				
			}
			else{
				$out['error'] = true;
				$out['message'] = 'File Uploaded but not Saved';
			}
		
		}
	}
	else{
		$out['error'] = true;
		$out['message'] = 'Upload Failed. File empty!';
	}

	echo json_encode($out);
?>

Thursday, January 13, 2022

AngularJs Simple Shopping Cart

AngularJs Simple Shopping Cart

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/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
index.html
//index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" name = "viewport" content = "width=device-width, initial-scale=1" />
<title>AngularJs Shopping Cart</title>
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"/>
</head>
<body ng-app="shoppingcart" ng-controller="shoppingCTR">
	<nav class="navbar navbar-expand-lg navbar-light bg-light">
	  <div class="container-fluid">
		<a class="navbar-brand" href="#">Cairocoders</a>
		<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
		  <span class="navbar-toggler-icon"></span>
		</button>
		<div class="collapse navbar-collapse" id="navbarNav">
		  <ul class="navbar-nav">
			<li class="nav-item">
			  <a class="nav-link active" aria-current="page" href="#">Home</a>
			</li>
		  </ul>
		</div>
	  </div>
	</nav>
	
	<div class="container">
	<div class="row">
		<h3 class = "text-primary">AngularJs Shopping Cart</h3>
		<hr style = "border-top:1px dotted #ccc;"/>
		<div id = "bg-background" class="col-8">
			<h4>PRODUCTS<h4>
			<hr style = "border-top:1px groovy #ccc;">
			<div id = "product">
				<div id = "p_list" ng-repeat = "product in products ">
					<span style="font-size:16px;">{{product.p_name}}</span>
					<center><img ng-src = "{{product.p_image}}"/></center>
					<div><label style="font-size:14px;">Price: ₱{{product.p_price}}</label></div>
					<center><button type = "button" class="btn btn-primary" ng-click = "add_cart(product)"> Add to cart</button></center>
				</div>
			</div>
		</div>
		<div class="col-4">
			<div class = "panel panel-primary">
				<div class = "panel-heading">
					<h5>MY CART</h5>
				</div>
				<div class = "panel-body table-responsive">
					<table class = "table">
						<thead>
							<tr>
								<th>Product</th>
								<th>Price</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<tr ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
								<td>{{cart.p_name}}</td>
								<td>₱{{cart.p_price}}</td>
								<td><button type = "button" ng-click = "remove_cart(cart)" class = "btn btn-danger"> X</button></td>
							</tr>
							<tr>
								<td align = "right">Total</td>
								<td>₱{{total}}</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		</div>
	</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
var app = angular.module("shoppingcart", [])
.controller("shoppingCTR", function($scope){
	$scope.carts=[];
	$scope.products = [
		{p_id: "1", p_name: "Dell Inspiron 15 3501", p_image: "images/1.jpg", p_price: 5900},
		{p_id: "2", p_name: "Asus X515 11th Gen intel", p_image: "images/2.jpg", p_price: 6800},
		{p_id: "3", p_name: "Lenovo IdealPad 3", p_image: "images/3.jpg", p_price: 4800},
	];
				
	$scope.add_cart = function(product){
		if(product){
			$scope.carts.push({p_id: product.p_id, p_name: product.p_name, p_price: product.p_price});
		}	
	}
						
	$scope.total = 0;
				
	$scope.setTotals = function(cart){
		if(cart){
			$scope.total += cart.p_price;
		}
	}
				
	$scope.remove_cart = function(cart){
		if(cart){
			$scope.carts.splice($scope.carts.indexOf(cart), 1);
			$scope.total -= cart.p_price;
		}
	}
});
</script>
<style>
#bg-background{
	background-color:#fff;
	padding:10px;
	border-radius:5px;
}
#product{
	padding:5px;
	clear:both;
}
#p_list{
	width:200px;
	max-width:200px;
	height:260px;
	padding:5px;
	border:1px solid #000;
	float:left;
	margin:15px;
}
#p_list img{
	height:150px; 
	width:150px;
}
</style>
</body>	
</html>

Wednesday, January 12, 2022

AngularJS Keypress Event Enter

AngularJS Keypress Event Enter

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

index.html
//index.html
<!DOCTYPE html>
<html ng-app="appkeypress">
<head>
	<meta charset="utf-8">
	<title>AngularJS Keypress Event Enter </title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
	<div class="container">
		<h1 class="page-header text-center">AngularJS Keypress Event Enter</h1>
		<div class="col-sm-4 col-sm-offset-4">
			<input type="text" class="form-control" ng-model="myinput" my-enter="alertInput()">
		</div>
	</div>
<script>
	var app = angular.module('appkeypress', []);

	app.directive('myEnter', function () {
	    return function ($scope, element, attrs) {
	        element.bind("keydown keypress", function (event) {
	            if(event.which === 13) {
	                $scope.$apply(function (){
	                    $scope.$eval(attrs.myEnter);
	                });

	                event.preventDefault();
	            }
	        });
	    };
	});

	app.controller('myCtrl', function($scope){
		$scope.alertInput = function(){
			alert($scope.myinput);
		}
	});
</script>
</body>
</html>

Angular JS Ui-Router Toggle Active page

Angular JS Ui-Router Toggle Active page

index.html
//index.html
<!DOCTYPE html>
<html ng-app="activemenu">
<head>
	<title>Angular JS Ui-Router Toggle Active page</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
</head>
<body>
<nav ng-controller="mainCtrl" class="navbar navbar-default">
	<div class="container">
	    <div class="navbar-header">
		    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
		        <span class="sr-only">Toggle navigation</span>
		        <span class="icon-bar"></span>
		        <span class="icon-bar"></span>
		        <span class="icon-bar"></span>
		    </button>
	     	<a class="navbar-brand" href="#">Cairocoders</a>
	    </div>
	    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
	      	<ul class="nav navbar-nav">
	        	<li ng-class="active('/home')"><a ui-sref="home">Home</a></li>
	        	<li ng-class="active('/about')"><a ui-sref="about">About</a></li>
	        	<li ng-class="active('/blog')"><a ui-sref="blog">Blog</a></li>
	      	</ul>
	    </div>
	</div>
</nav>
<div class="container">
	<div ui-view></div>
</div>
<script>
var app = angular.module('activemenu', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    
    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
              
        .state('about', {
            url: '/about',
           	templateUrl: 'about.html', 
            
        })

        .state('blog', {
            url: '/blog',
            templateUrl: 'blog.html', 
        });
        
});

app.controller('mainCtrl', function($scope, $location){
	$scope.active = function(path){
		 return ($location.path() === path) ? 'active' : '';
	}
});
</script>
</body>
</html>
home.html
//home.html
<h4>This is the Home Page</h4>
<p><b>Home Tab</b> is active</p>
about.html
//about.html
<h4>This is the About Page</h4>
<p><b>About Tab</b> is active</p>
blog.html
//blog.html
<h4>This is the Blog Page</h4>
<p><b>Blog Tab</b> is active</p>

Saturday, January 8, 2022

AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort

AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css

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

dirPagination - AngularJS module for paginating

https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination

https://github.com/michaelbromley/angularUtils/blob/master/src/directives/pagination/dirPagination.js

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `created_at` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`, `created_at`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '2020-01-09'),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '2020-02-15'),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '2020-03-01'),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '2020-01-24'),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '2020-01-11'),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '2020-02-23'),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456, '2020-03-04'),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568, '2020-04-28'),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456, '2020-01-12'),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '2020-02-06'),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '2020-03-21'),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '2020-04-14'),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '2020-01-29'),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465, '2020-02-22'),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '2020-03-10'),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '2020-04-26'),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '2020-01-17'),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '2020-02-01'),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '2020-03-19'),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '2020-04-21');

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularJS PHP Mysqli CRUD with Pagination Search and Sort </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body ng-app="employeeapp" ng-controller="employeeCTR" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS PHP Mysqli CRUD (Create, Read, Update and Delete) with Pagination, Search and Sort</h1>
    <div class="row">
		<div class="col-md-12">
			<div class="alert alert-success text-center" ng-show="success">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-check"></i> {{ successMessage }}
			</div>
			<div class="alert alert-danger text-center" ng-show="error">
				<button type="button" class="close" ng-lick="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-warning"></i> {{ errorMessage }}
			</div>
			<div class="row">
				<div class="col-md-12">
					<button href="" class="btn btn-primary" ng-click="showAdd()"><i class="fa fa-plus"></i> Add New New Employee</button>
					<span class="pull-right">
						<input type="text" ng-model="search" class="form-control" placeholder="Search">
					</span>
				</div>
			</div>
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                        <th ng-click="sort('name')" class="text-center">Name
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='name'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='name'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                        </th>
                        <th ng-click="sort('position')" class="text-center">Position
	                        <span class="pull-right">
	                       		<i class="fa fa-sort gray" ng-show="sortKey!='position'"></i>
	                       		<i class="fa fa-sort" ng-show="sortKey=='position'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
	                       	</span>
                        </th>
                        <th ng-click="sort('office')" class="text-center">Office
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='office'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='office'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                       	</th>                        
						<th class="text-center">Age</th>
                       	<th class="text-center">Salary</th>
                       	<th class="text-center">Action</th>
                    </tr>
                </thead>
				<tbody>
					<tr dir-paginate="rs in employee|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
						<td>{{ rs.name }}</td>
						<td>{{ rs.position }}</td>
						<td>{{ rs.office }}</td>
						<td>{{ rs.age }}</td>
						<td>$ {{ rs.salary }}</td>
						<td>
							<button type="button" class="btn btn-success" ng-click="showEdit(); selectEmployee(rs);"><i class="fa fa-edit"></i> Edit</button> 
							<button type="button" class="btn btn-danger" ng-click="showDelete(); selectEmployee(rs);"> <i class="fa fa-trash"></i> Delete</button>
						</td>

					</tr>
				</tbody>
			</table>
			<div class="pull-right" style="margin-top:-30px;">
				<dir-pagination-controls
				   max-size="5"
				   direction-links="true"
				   boundary-links="true" >
				</dir-pagination-controls>
				

			</div>
  
  
		</div>
	</div>
	<?php include('modal.php'); ?>
</div>
<script src="dirPaginate.js"></script>
<script src="angular.js"></script>
<style>
.pagination {
    display: inline-block;
    padding-left: 0;
    margin: 20px 0;
    border-radius: 4px;
}
.pagination>li {
    display: inline;
}
.pagination>li:first-child>a, .pagination>li:first-child>span {
    margin-left: 0;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}
.pagination>.disabled>a, .pagination>.disabled>a:focus, .pagination>.disabled>a:hover, .pagination>.disabled>span, .pagination>.disabled>span:focus, .pagination>.disabled>span:hover {
    color: #777;
    cursor: not-allowed;
    background-color: #fff;
    border-color: #ddd;
}
.pagination>li>a, .pagination>li>span {
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #337ab7;
    text-decoration: none;
    background-color: #fff;
    border: 1px solid #ddd;
}
.pagination>.active>a, .pagination>.active>a:focus, .pagination>.active>a:hover, .pagination>.active>span, .pagination>.active>span:focus, .pagination>.active>span:hover {
    z-index: 3;
    color: #fff;
    cursor: default;
    background-color: #337ab7;
    border-color: #337ab7;
}
</style>
</body>
</html>
angular.js
//angular.js
var app = angular.module('employeeapp', ['angularUtils.directives.dirPagination']);
app.controller('employeeCTR',function($scope, $http, $window){
	$scope.AddModal = false;
    $scope.EditModal = false;
    $scope.DeleteModal = false;

    $scope.errorname = false;

    $scope.showAdd = function(){
    	$scope.name = null;
    	$scope.position = null;
    	$scope.office = null;
    	$scope.errorname = false;
    	$scope.errorposition = false;
    	$scope.erroroffice = false;
    	$scope.AddModal = true;
    }
  
	$scope.fetch = function(){
        $http({
			method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.employee = data.data;      
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.sort = function(keyname){
        $scope.sortKey = keyname;   
        $scope.reverse = !$scope.reverse;
    }

    $scope.clearMessage = function(){
    	$scope.success = false;
    	$scope.error = false;
    }

    $scope.addnew = function(){
        $http({
			method: 'POST',
            url: 'add.php',
			data:{name:$scope.name, position:$scope.position, office:$scope.office}
        }).then(function (data){
            console.log(data)
        	if(data.data.name){
        		$scope.errorname = true;
        		$scope.errorposition = false;
        		$scope.erroroffice = false;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('name').focus();
        	}
        	else if(data.data.position){
        		$scope.errorname = false;
        		$scope.errorposition = true;
        		$scope.erroroffice = false;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('position').focus();
        	}
        	else if(data.data.office){
        		$scope.errorname = false;
        		$scope.errorposition = false;
        		$scope.erroroffice = true;
        		$scope.errorMessage = data.data.message;
        		$window.document.getElementById('office').focus();
        	}
        	else if(data.data.error){
        		$scope.errorname = false;
        		$scope.errorposition = false;
        		$scope.erroroffice = false;
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        	}
        	else{
        		$scope.AddModal = false;
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        		$scope.fetch();
        	}     
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.selectEmployee = function(employee){
    	$scope.clickEmployee = employee;
    }

    $scope.showEdit = function(){
    	$scope.EditModal = true;
    }

    $scope.updateEmployee = function(){
        $http({
			method: 'POST',
            url: 'edit.php',
			data: $scope.clickEmployee
        }).then(function (data){
            console.log(data)
        	if(data.error){
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        		$scope.fetch();
        	}
        	else{
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        	}     
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.showDelete = function(){
    	$scope.DeleteModal = true;
    }

    $scope.deleteEmployee = function(){
        $http({
			method: 'POST',
            url: 'delete.php',
			data: $scope.clickEmployee
        }).then(function (data){
            console.log(data)
        	if(data.data.error){
        		$scope.error = true;
        		$scope.errorMessage = data.data.message;
        	}
        	else{
        		$scope.success = true;
        		$scope.successMessage = data.data.message;
        		$scope.fetch();
        	}  
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

});
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();
	$sql = "SELECT * FROM employee";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
modal.php
//modal.php
<!-- Add Modal -->
<div class="myModal" ng-show="AddModal">
	<div class="modalContainer">
		<div class="modalHeader">
			<span class="headerTitle">Add New Employee</span>
			<button class="closeBtn pull-right" ng-click="AddModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Name:</label>
				<input type="text" class="form-control" ng-model="name" id="name">
				<span class="pull-right input-error" ng-show="errorFirstname">{{ errorMessage }}</span>
			</div>
			<div class="form-group">
				<label>Position:</label>
				<input type="text" class="form-control" ng-model="position" id="position">
				<span class="pull-right input-error" ng-show="errorposition">{{ errorMessage }}</span>
			</div>
			<div class="form-group">
				<label>Office:</label>
				<input type="text" class="form-control" ng-model="office" id="office">
				<span class="pull-right input-error" ng-show="erroroffice">{{ errorMessage }}</span>
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="AddModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-primary" ng-click="addnew()"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Edit Modal -->
<div class="myModal" ng-show="EditModal">
	<div class="modalContainer">
		<div class="editHeader">
			<span class="headerTitle">Edit Employee</span>
			<button class="closeEditBtn pull-right" ng-click="EditModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Name:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.name">
			</div>
			<div class="form-group">
				<label>Position:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.position">
			</div>
			<div class="form-group">
				<label>Office:</label>
				<input type="text" class="form-control" ng-model="clickEmployee.office">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="EditModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-success" ng-click="EditModal = false; updateEmployee();"><span class="glyphicon glyphicon-check"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Delete Modal -->
<div class="myModal" ng-show="DeleteModal">
	<div class="modalContainer">
		<div class="deleteHeader">
			<span class="headerTitle">Delete Employee</span>
			<button class="closeDelBtn pull-right" ng-click="DeleteModal = false">×</button>
		</div>
		<div class="modalBody">
			<h5 class="text-center">Are you sure you want to delete</h5>
			<h2 class="text-center">{{clickEmployee.name}}</h2>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" ng-click="DeleteModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-danger" ng-click="DeleteModal = false; deleteEmployee(); "><span class="glyphicon glyphicon-trash"></span> Yes</button>
			</div>
		</div>
	</div>
</div>
edit.php
//edit.php
<?php
	include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

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

    $name = $data->name;
    $position = $data->position;
    $office = $data->office;
    $id = $data->id;

   	$sql = "UPDATE employee SET name = '$name', position = '$position', office = '$office' WHERE id = '$id'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Employee updated Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot update';
   	}

    echo json_encode($out);
?>
delete.php
//delete.php
<?php
	include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

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

    $id = $data->id;

   	$sql = "DELETE FROM employee WHERE id = '$id'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Employee deleted Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot delete';
   	}

    echo json_encode($out);
?>
add.php
//add.php
<?php
    include('conn.php');
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false, 'name' => false, 'position' => false, 'office' => false);

    $name = $data->name;
    $position = $data->position;
    $office = $data->office;

    if(empty($name)){
        $out['name'] = true;
        $out['message'] = 'name is required'; 
    } 
    elseif(empty($position)){
        $out['position'] = true;
        $out['message'] = 'position is required'; 
    }
    elseif(empty($office)){
        $out['office'] = true;
        $out['message'] = 'office is required'; 
    }
    else{
        $sql = "INSERT INTO employee (name, position, office, age, salary) VALUES ('$name', '$position', '$office', '25', '99')";
        $query = $conn->query($sql);

        if($query){
            $out['message'] = 'New Employee Added Successfully';
        }
        else{
            $out['error'] = true;
            $out['message'] = 'Cannot Add';
        }
    }
        
    echo json_encode($out);
?>
style.css
//style.css
.gray{
	color:gray;
}

.input-error{
	font-size:12px;
	color:#f44336;
}

.myModal{
	position:fixed;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background: rgba(0, 0, 0, 0.4);
	z-index:100;
}

.modalContainer{
	width: 555px;
	background: #FFFFFF;
	margin:auto;
	margin-top:10px;
}

.modalHeader{
	padding:10px;
	background: #008CBA;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.editHeader{
	padding:10px;
	background: #4CAF50;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.deleteHeader{
	padding:10px;
	background: #f44336;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.modalBody{
	padding:30px;
}

.modalFooter{
	height:36px;
}

.footerBtn{
	margin-right:10px;
	margin-top:-9px;
}

.closeBtn{
	background: #008CBA;
	color: #FFFFFF;
	border:none;
}

.closeEditBtn{
	background: #4CAF50;
	color: #FFFFFF;
	border:none;
}

.closeDelBtn{
	background: #f44336;
	color: #FFFFFF;
	border:none;
}

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);    
?>

Thursday, January 6, 2022

AngularJS Preview before Upload

AngularJS Preview before Upload

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

//index.html
<!DOCTYPE html>
<html >
<head>
	<title>AngularJS Preview before Upload</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="angularupload" ng-controller="uploader">
<div class="container">
	<h1 class="page-header text-center">AngularJS Preview before Upload</h1>
	<div class="row">
		<div class="col-md-3">
			<h3 class="text-center">Upload File</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files">
		</div>
		<div class="col-md-9">
			<div ng-show="filepreview">
			<img ng-src="{{filepreview}}" height="300px" width="300px">
			<h4>Filename: {{ name }}</h4>
			<h4>Size: {{ size }}</h4>
			</div>
		</div>
	</div>
</div>
<script>
var app = angular.module('angularupload', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
      $scope: {
        fileinput: "=",
        filepreview: "="
      },
      link: function($scope, element, attributes) {
        element.bind("change", function(changeEvent) {
          	$scope.fileinput = changeEvent.target.files[0];
          	var reader = new FileReader();
          	reader.onload = function(loadEvent) {
            	$scope.$apply(function() {
            		$scope.filepreview = loadEvent.target.result;
            	});
          	}
          	reader.readAsDataURL($scope.fileinput);
          	$scope.name = $scope.fileinput.name;
          	$scope.size = $scope.fileinput.size;
        });
      }
    }
}]);
app.controller('uploader', function($scope, $http){

});
</script>
</body>
</html>

Friday, December 24, 2021

Angular JS PHP Mysql Login

Angular JS PHP Mysql Login

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

CREATE TABLE `tbluser` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `username` varchar(150) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `tbluser` (`id`, `name`, `username`, `password`) VALUES
(1, 'Cairocoders Ednalan', 'cairocoders', '123456'),
(2, 'tutorial101', 'clded25', '123456'),
(3, 'Clydey Ednalan', 'clyde0130', '123456');

ALTER TABLE `tbluser`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `tbluser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html ng-app="myapp" ng-controller="controller">
<head>
<title>Angular JS PHP Mysql Login</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> 
</head>
<body>
<div class="container">
	<center><h2 style="color:#fff;">Angular JS PHP Mysql Login</h2></center>
    <div class="card card-login mx-auto text-center bg-dark">
        <div class="card-header mx-auto bg-dark">
            <span> <img src="myglogo.png" width="100" alt="Logo"/> </span><br/>
            <span class="logo_title mt-5"> Login Account </span>
        </div>
        <div class="card-body">
            <form ng-submit="myFunct()">
                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                    </div>
                    <input type="text" class="form-control" placeholder="Username" name="username" id="username" ng-model="username" autofocus>
                </div>

                <div class="input-group form-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                    </div>
                    <input type="password" class="form-control" placeholder="Password" name="password" id="password" ng-model="password">
                </div>

                <div class="form-group">
					<button type="submit" class="btn btn-outline-danger float-right login_btn" ng-click="login()"><span class="glyphicon glyphicon-log-in"></span> {{btnName}}</button>
                </div>
            </form>
        </div>
		<div ng-if="message">
		<div class="alert alert-success"><center>{{message}}</center></div>
		</div>
    </div>
</div>
<script>
var app = angular.module("myapp", []);
app.controller("controller", function($scope, $http) {
	$scope.btnName = "Login";
	
	$scope.error = false;
    $scope.success = false;
	
	$scope.login = function() {
		if ($scope.username == null) {
            alert("Please input Username");
        } 
        else if ($scope.password == null) {
            alert("Please input Password");
        }  
        else {
        	$scope.btnName = "Logging in...";
        	$scope.alert = "Checking Account. Please Wait...";
			
			$http({
				method: 'POST',
				url: 'login.php',
				data:{username:$scope.username, password:$scope.password}
			}).then(function (data){
				console.log(data)
				if(data.error){
					$scope.error = true;
					$scope.success = false;
					$scope.message = data.data.message;
            		setTimeout(function() {
            			$scope.btnName = "Login";
            			$scope.$apply();
  					}, 3000);
				}
				else{
					$scope.success = true;
					$scope.error = false;
					$scope.message = data.data.message;
            		setTimeout(function() {
	            		$scope.username = null;
	                	$scope.password = null;
	                	$scope.btnName = "Login";
	                	$scope.$apply();
	                }, 3000);
	                setTimeout(function() {	
            			window.location.reload();
            		}, 4000);
				}
				
			},function (error){
				console.log(error, 'can not get data.');
			});
        }
	}
});
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
login.php
//login.php
<?php
	include('conn.php');
	session_start();
	$data = json_decode(file_get_contents("php://input"));
	
	$out = array('error' => false);
	$username = mysqli_real_escape_string($conn, $data->username);
    $password = mysqli_real_escape_string($conn, $data->password);
	
	$query=$conn->query("select * from tbluser where username='$username' and password='$password'");
    if($query->num_rows > 0){
		$row=$query->fetch_array();
		$_SESSION['user']=$row['id'];
        $out['message'] = "Login Successful. Username: $username Password: $password";
    }
    else{
        $out['error'] = true;
        $out['message'] = "Login Failed. User not Found!"; 
    }
  
    echo json_encode($out);
?>
home.php
//home.php
<?php
	session_start();
	if(!isset($_SESSION['user'])){
		header('location:index.php');
	}
	include('conn.php');
	$query=$conn->query("select * from tbluser where id='".$_SESSION['user']."'");
	$row=$query->fetch_array();
?>
<!DOCTYPE html>
<html>
<head>
<title>Angular JS PHP Mysql Login</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-md-6">
			<h2>Angular JS PHP Mysql Login</h2>
		</div>
	</div>
	<hr>
    <div class="row">
    	<div class="col-md-4">
    		<h2><center>Welcome, <?php echo $row['username']; ?></center></h2>
    		<center><a href="logout.php" class="btn btn-danger"> Logout</a></center>
    	</div>
    </div>
</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>
style.css
//style.css
body {
	background: #000 !important;
}
.card {
	border: 1px solid #28a745;
}
.card-login {
    margin-top:30px;
    padding: 18px;
    max-width: 30rem;
}

.card-header {
    color: #fff;
    /*background: #ff0000;*/
    font-family: sans-serif;
    font-size: 20px;
    font-weight: 600 !important;
    margin-top: 10px;
    border-bottom: 0;
}

.input-group-prepend span{
    width: 50px;
    background-color: #ff0000;
    color: #fff;
    border:0 !important;
}

input:focus{
    outline: 0 0 0 0  !important;
    box-shadow: 0 0 0 0 !important;
}

.login_btn{
    width: 130px;
}

.login_btn:hover{
    color: #fff;
    background-color: #ff0000;
}

.btn-outline-danger {
    color: #fff;
    font-size: 18px;
    background-color: #28a745;
    background-image: none;
    border-color: #28a745;
}

.form-control {
    display: block;
    width: 100%;
    height: calc(2.25rem + 2px);
    padding: 0.375rem 0.75rem;
    font-size: 1.2rem;
    line-height: 1.6;
    color: #28a745;
    background-color: transparent;
    background-clip: padding-box;
    border: 1px solid #28a745;
    border-radius: 0;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.input-group-text {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    padding: 0.375rem 0.75rem;
    margin-bottom: 0;
    font-size: 1.5rem;
    font-weight: 700;
    line-height: 1.6;
    color: #495057;
    text-align: center;
    white-space: nowrap;
    background-color: #e9ecef;
    border: 1px solid #ced4da;
    border-radius: 0;
}

AngularJS PHP Mysql Pagination

AngularJS PHP Mysql Pagination

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

https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination

dirPagination libs Its very simple and easy to use

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Pagination</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="dirPaginate.js"></script>
</head>
<body>
<div class="container" ng-app="paginationApp" ng-controller="paginationController">
   <br />
    <h3 align="center">AngularJS PHP Mysql Pagination </h3>
    <br />
    <div class="table-responsive">
    <table class="table table-striped table-bordered">
		<thead>
		  <tr>
		   <th width="50">ID</th>
		   <th>Firts Name</th>
		   <th>Last Name</th>
		   <th>Address</th>
		  </tr>
		</thead>
		<tbody>
		  <tr dir-paginate="rs in allData|itemsPerPage:5">
		   <td>{{ rs.id }}</td>
		   <td>{{ rs.firstname }}</td>
		   <td>{{ rs.lastname }}</td>
		   <td>{{ rs.address }}</td>
		  </tr>
		</tbody>
    </table>
    </div>
    <div align="right">
		<dir-pagination-controls max-size="5" direction-links="true" boundary-links="true" >
		</dir-pagination-controls>
    </div>
</div>
<script>
var pagination_app = angular.module('paginationApp', ['angularUtils.directives.dirPagination']);
	pagination_app.controller('paginationController', function($scope, $http){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.allData = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
	});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
$query = "SELECT * FROM members ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
		{
		  $data[] = $row;
		}
	echo json_encode($data);
}
?>

AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS

AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS

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

Chart.js
chart.js is a simple, clean and engaging HTML5 based JavaScript charts. Chart.js is an easy way to include animated, interactive graphs on your website for free.

https://www.chartjs.org/

https://www.chartjs.org/docs/latest/

CREATE TABLE `productsales` (
  `saleid` int(11) NOT NULL,
  `productid` int(11) NOT NULL,
  `amount` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `productsales`
  ADD PRIMARY KEY (`saleid`);

ALTER TABLE `productsales`
  MODIFY `saleid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
  
  
CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `productname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `products` (`id`, `productname`) VALUES
(1, 'Ipad'),
(2, 'Iphone'),
(3, 'Macbook'),
(4, 'Mac');

ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

index.html
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
	<title>AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
	<style type="text/css">
		canvas{
			margin:auto;
		}
		.alert{
			margin-top:20px;
		}
	</style>
</head>
<body ng-controller="myCtrl">
<div class="container">
	<div class="row"><h1>AngularJS PHP MySQLi Pie Doughnut Chart using ChartJS</h1>
		<div class="col-sm-3 col-md-offset-1" ng-init="fetchproducts()">
			<h3 class="page-header text-center">Add Purchase</h3>
			<div class="form-group">
				<label>Select Product:</label>
				<select ng-model="productid" class="form-control" name="productid">
					<option ng-repeat="rs in products" value="{{rs.id}}">{{rs.productname}}</option>
				</select>
			</div>
			<div class="form-group">
				<label>Amount:</label>
				<input type="text" class="form-control" name="amount" ng-model="amount">
			</div>
			<button type="button" ng-click="purchase()" class="btn btn-primary">Buy</button>
			<div class="alert alert-success text-center" ng-show="success">
				<button type="button" class="close" aria-hidden="true" ng-click="clear()">×</button>
				{{ message }}
			</div>
			<div class="alert alert-danger text-center" ng-show="error">
				<button type="button" class="close" aria-hidden="true" ng-click="clear()">×</button>
				{{ message }}
			</div>
		</div>
		<div class="col-sm-7" ng-init="fetchsales()">
			<h3 class="page-header text-center">Product Sales Chart</h3>
			<canvas id="dvCanvas" height="400" width="400"></canvas>
	    </div>
	</div>
</div>
<script>
var app = angular.module('app', []);
 
app.controller('myCtrl', function ($scope, $http) {
 
    $scope.error = false;
    $scope.success = false;
 
    $scope.fetchproducts = function(){
		$http({
            method: 'GET',
            url: 'fetchproducts.php',
        }).then(function (data){
            console.log(data)
            $scope.products = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    $scope.purchase = function(){
		$http({
            method: 'POST',
            url: 'purchase.php',
			data:{amount:$scope.amount, productid:$scope.productid}
        }).then(function (data){
            console.log(data)
            if(data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.message = data.data.message;
            }
            else{
                $scope.success = true;
                $scope.error = false;
                $scope.message = data.data.message;
                $scope.fetchsales();
                $scope.buy = '';
            }
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    //this fetches the data for our table
    $scope.fetchsales = function(){
		$http({
            method: 'GET',
            url: 'fetchsales.php',
        }).then(function (data){
            console.log(data)
            var ctx = document.getElementById("dvCanvas").getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'pie', // change the value of pie to doughtnut for doughnut chart
                data: {
                    datasets: [{
                        data: data.data.total,
                        backgroundColor: ['blue', 'green', 'red', 'yellow']
                    }],
                    labels: data.data.productname
                },
                options: {
                    responsive: false
                }
            });
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
 
    $scope.clear = function(){
        $scope.error = false;
        $scope.success = false;
    }
 
});
</script>
</body>
</html>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
fetchproducts.php
//fetchproducts.php
<?php
include('dbcon.php');

$out = array();
 
$sql = "SELECT * FROM products";
$query = $conn->query($sql);
 
while($row=$query->fetch_array()){
	$out[] = $row;
}
echo json_encode($out);
?>
purchase.php
//purchase.php
<?php
	include('dbcon.php');
 
	$out = array('error' => false);
 
	$data = json_decode(file_get_contents("php://input"));
 
	$productid = $data->productid;
	$amount = $data->amount;
 
	$sql = "INSERT INTO productsales (productid, amount) VALUES ('$productid', '$amount')";
	$query = $conn->query($sql);
 
	if($query){
		$out['message'] = "Purchase added successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Cannot add purchase"; 
	}
 
	echo json_encode($out);
?>
fetchsales.php
//fetchsales.php
<?php
	include('dbcon.php');
 
	$out = array();
 
	$sql = "SELECT *, sum(amount) AS total FROM productsales LEFT JOIN products ON products.id=productsales.productid GROUP BY productsales.productid";
	$query = $conn->query($sql);
 
	while($row=$query->fetch_array()){
	    $out['total'][] = $row['total'];
	    $out['productname'][] = $row['productname'];
	}
 
	echo json_encode($out);
?>

Thursday, December 23, 2021

AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap

AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap

https://angularjs.org/ version 1.8.2

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

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

Database Table

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545);

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
index.php
//index.php
<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS Live Data Search with PHP Mysql and bootstrap</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" ng-app="angularlivesearch" ng-controller="search_controller" ng-init="fetchData()">
	<br />
	<h3 align="center">AngularJS 1.8.2 Live Data Search with PHP Mysql and bootstrap</h3>
	<br />
	<div class="form-group">
		<div class="input-group">
		 <input type="text" name="search_query" ng-model="search_query" ng-keyup="fetchData()" placeholder="Search" class="form-control" />
		</div>
	</div>
	<br />
	<table class="table table-striped table-bordered">
		<thead>
		 <tr>
		  <th>Name</th>
		  <th>Position</th>
		  <th>office</th>
		  <th>age</th>
		  <th>Salary</th>
		 </tr>
		</thead>
		<tbody>
		 <tr ng-repeat="data in searchData">
		  <td>{{ data.name }}</td>
		  <td>{{ data.position }}</td>
		  <td>{{ data.office }}</td>
		  <td>{{ data.age }}</td>
		  <td>{{ data.salary }}</td>
		 </tr>
		</tbody>
	</table>
</div>
  
<script>
var app = angular.module('angularlivesearch', []);
	app.controller('search_controller', function($scope, $http){
	$scope.fetchData = function(){
		$http({
            method: 'POST',
            url: 'fetch.php',
			data:{search_query:$scope.search_query}
        }).then(function (data){
            console.log(data)
            $scope.searchData = data.data;
        },function (error){
            console.log(error, 'can not get data.');
        });
	};
});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");

$form_data = json_decode(file_get_contents("php://input"));

$query = '';
$data = array();

if(isset($form_data->search_query))
{
	$search_query = $form_data->search_query;
	 $query = "
	 SELECT * FROM employee 
	 WHERE (name LIKE '%$search_query%' 
	 OR position LIKE '%$search_query%' 
	 OR office LIKE '%$search_query%') 
	";
}else{
	$query = "SELECT * FROM employee ORDER BY name ASC";
}

$statement = $connect->prepare($query);

if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
	  $data[] = $row;
	}
	 echo json_encode($data);
}
?>

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

https://angularjs.org/ version 1.8.2

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

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
index.html
//index.html
<html>  
<head>  
<title>AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>  
<body>  
<div class="container"><br />
    <h3 align="center">AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</h3><br />
    <div class="table-responsive" ng-app="angularinlinetablecrud" ng-controller="liveController" ng-init="fetchData()">
                <div class="alert alert-success alert-dismissible" ng-show="success" >
                    <a href="#" class="close" data-dismiss="alert" ng-click="closeMsg()" aria-label="close">×</a>
                    {{successMessage}}
                </div>
                <form name="testform" ng-submit="insertData()">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Address</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" ng-model="addData.firstname" class="form-control" placeholder="Enter First Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.lastname" class="form-control" placeholder="Enter Last Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.address" class="form-control" placeholder="Enter Address" ng-required="true" /></td>
                                <td><button type="submit" class="btn btn-success btn-sm" ng-disabled="testform.$invalid">Add</button></td>
                            </tr>
                            <tr ng-repeat="data in namesData" ng-include="getTemplate(data)">
                            </tr>
                            
                        </tbody>
                    </table>
                </form>
                <script type="text/ng-template" id="display">
                    <td>{{data.firstname}}</td>
                    <td>{{data.lastname}}</td>
                    <td>{{data.address}}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
                    </td>
                </script>
                <script type="text/ng-template" id="edit">
                    <td><input type="text" ng-model="formData.firstname" class="form-control"  /></td>
                    <td><input type="text" ng-model="formData.lastname" class="form-control" /></td>
                    <td><input type="text" ng-model="formData.address" class="form-control" /></td>
                    <td>
                        <input type="hidden" ng-model="formData.data.id" />
                        <button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
                        <button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
                    </td>
                </script>   

				<!--<div id="output">{{ foo }}</div> -->
   </div>  
  </div>
<script>
var app = angular.module('angularinlinetablecrud', []);

app.controller('liveController', function($scope, $http){

    $scope.formData = {};
    $scope.addData = {};
    $scope.success = false;

    $scope.getTemplate = function(data){ //alert(data.id);
        if (data.id === $scope.formData.id)
        {
            return 'edit';
        }
        else
        {
            return 'display';
        }
    };

    $scope.fetchData = function(){
		   $http({
			  method: 'GET',
			  url: 'select.php'
		   }).then(function (data){
				console.log(data)
				$scope.namesData = data.data;
				//$scope.foo = data.data;
		   },function (error){
				console.log(error, 'can not get data.');
		   });
    };

    $scope.insertData = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:$scope.addData,
        }).then(function(data){ alert(data.data.message);
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.addData = {};
        });
    };

    $scope.showEdit = function(data) {
        $scope.formData = angular.copy(data);
    };

    $scope.editData = function(){
        $http({
            method:"POST",
            url:"edit.php",
            data:$scope.formData,
        }).then(function(data){
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.formData = {};
        });
    };

    $scope.reset = function(){
        $scope.formData = {};
    };

    $scope.closeMsg = function(){
        $scope.success = false;
    };

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"delete.php",
                data:{'id':id}
            }).then(function(data){
                $scope.success = true;
                $scope.successMessage = data.data.message;
                $scope.fetchData();
            }); 
        }
    };

});
</script>
</body>  
</html>  
db.php
//db.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>
select.php
//select.php
<?php  
include('db.php');

$query = "SELECT * FROM members ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}
?>
insert.php
//insert.php
<?php  
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address
);

$query = "
 INSERT INTO members 
 (firstname, lastname, address) VALUES 
 (:firstname, :lastname, :address)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $message = 'Data Inserted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
edit.php
//edit.php
<?php  
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address,
 ':id'    => $form_data->id
);

$query = "
 UPDATE members 
 SET firstname = :firstname, lastname = :lastname , address = :address 
 WHERE id = :id
";

$statement = $connect->prepare($query);
if($statement->execute($data))
{
 $message = 'Data Edited';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
delete.php
//delete.php
<?php
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$query = "DELETE FROM members WHERE id = '".$form_data->id."'";

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>

Thursday, December 16, 2021

AngularJS User Registraion Form

AngularJS User Registraion Form

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

registraion.html
//registraion.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS User Registraion Form</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  </head>
<body>
	<div ng-app = "registrationform" class = "container">
	  <div style="text-align:center;color:blue">
		<h3><b>AngularJS User Registraion Form</b></h3>
	  </div>
		<div ng-controller = "FormController">
		  <div align="right">
			<a href="#" ng-click="searchUser()">{{title}}</a>
		  </div>
		  <form role = "form" class="well" ng-hide="ifSearchUser">
			<div class = "form-group">
				<label for = "name"> Name:  </label>
				<input type = "text" id = "name" class = "form-control" placeholder = "Enter Name " ng-model = "newcontact.name">
			</div>
			<div class = "form-group">
				<label for = "email"> Email:  </label>
				<input type = "email" id = "email" class = "form-control" placeholder = "Enter Email " ng-model = "newcontact.email">
			</div>
			<div class = "form-group">
				<label for = "password"> Password:  </label>
				<input type = "password" id = "password" class = "form-control" placeholder = "Enter Password " ng-model = "newcontact.password">
			</div>
			<div class = "form-group">
				<label for = "phone"> Phone:  </label>
				<input type = "text" id = "phone" class = "form-control" placeholder = "Enter Phone " ng-model = "newcontact.phone">
			</div>
			<br>
			<input type="hidden" ng-model="newcontact.id">
			<input type="button" class="btn btn-primary" ng-click="saveContact()" class="btn btn-primary" value = "Submit">
		  </form>
			
		  <div><h4><b>Registered Users</b></h4>
			<table ng-if="contacts.length" class = "table table-striped table-bordered table-hover">
			  <thead>
				<tr class = "info">
					<th>Name</th>
					<th>Email</th>
					<th>Phone</th>
					<th ng-if="!ifSearchUser">Action</th>
				</tr>
				</thead>
				<tbody>
				<tr ng-repeat = "contact in contacts">
					 <td>{{ contact.name }}</td>
					 <td>{{ contact.email }}</td>
					 <td>{{ contact.phone }}</td>
	
					 <td ng-if="!ifSearchUser">
						<a href="#" ng-click="edit(contact.id)" role = "button" class = "btn btn-info">edit</a>  
						<a href="#" ng-click="delete(contact.id)" role = "button" class = "btn btn-danger">delete</a>
					</td>
				</tr>
				</tbody>
			</table>
		  <div ng-hide="contacts.length > 0">No Users Found</div>
		  </div>
		</div>
	</div>
<script>
var myApp = angular.module("registrationform", []);
myApp.service("ContactService" , function(){
	var uid = 1;
	var contacts = [{
		  'id' : 0,
				 'name' : 'Cairocoders Ednalan',
				 'email' : 'cairocoders@gmail.com',
				 'password': '123456',
				 'phone' : '123456789'}, {
		  'id' : 2,
				 'name' : 'clydey Ednalan',
				 'email' : 'clyde@gmail.com',
				 'password': '123456',
				 'phone' : '123456789'}];	
	
	this.save = function(contact)  
	{
		if(contact.id == null)                       
		{
			contact.id = uid++;
			contacts.push(contact);
		}
		else
		{
			for(var i in contacts)
			{
				if(contacts[i].id == contact.id)
				{
					contacts[i] = contact;
				}
			}
		}
	};
	
	this.get = function(id)
	{
		for(var i in contacts )
		{
			if( contacts[i].id == id)
			{
				return contacts[i];
			}
		}
	};
	
	//Delete a contact
	this.delete = function(id)
	{
		for(var i in contacts)
			{
				if(contacts[i].id == id)
				{
					contacts.splice(i,1);
				}
			}
	};	
	//Show all contacts
	this.list = function()
	{
		return contacts;
	}	;	
});
	
myApp.controller("FormController" , function($scope , ContactService){
    console.clear();
    
    $scope.ifSearchUser = false;
    $scope.title ="List of Users";
    
		$scope.contacts = ContactService.list();
		
		$scope.saveContact = function()
		{
		  console.log($scope.newcontact);
		  if($scope.newcontact == null || $scope.newcontact == angular.undefined)
		  return;
			ContactService.save($scope.newcontact);
			$scope.newcontact = {};
		};		
		$scope.delete = function(id)
		{
			ContactService.delete(id);
			if($scope.newcontact != angular.undefined && $scope.newcontact.id == id)
				{
					$scope.newcontact = {};
				}
		};		
		$scope.edit = function(id)
		{
			$scope.newcontact = angular.copy(ContactService.get(id));
		};		
		$scope.searchUser = function(){
		  if($scope.title == "List of Users"){
		    $scope.ifSearchUser=true;
		    $scope.title = "Back";
		  }
		  else
		  {
		    $scope.ifSearchUser = false;
		    $scope.title = "List of Users";
		  }		  
		};
});
</script>	
</body>
</html>

Related Post