article

Monday, January 31, 2022

AngularJS Select add Options with PHP MySQLi

AngularJS Select add Options with PHP MySQLi

Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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

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'),
(5, 'Dell Inspiron 15'),
(6, 'Mac Mini');

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

ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
index.html
//index.html
<!DOCTYPE html>
<html lang="en" ng-app="appselect">
<head>
<meta charset="utf-8">
<title>AngularJS Select add Options with PHP MySQLi</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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="selectController" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Select add Options with PHP MySQLi</h1>
    <div class="row">
		<div class="col-md-6">
			<h3>Add new Product</h3>
			<input type="text" placeholder="Product Name" class="form-control" ng-model="newProduct.productname"><br>
			<button type="button" class="btn btn-primary" ng-click="add()"> Save</button>
		</div>
		<div class="col-md-6">
			<h3>Select Product</h3>
			<select ng-model="selectedproduct" ng-options="x.productname for x in products" class="form-control">
			</select>
			<hr>
			<p><b>You selected:</b> {{selectedproduct.productname}}</p>
			<p><b>ID:</b> {{selectedproduct.id}}</p>
		</div>
	</div>
	
	<div class="row">
		<h3>Product Table</h3>
		<table class="table table-bordered table-striped">
			<thead>
				<tr>
					<th>Product ID</th>
					<th>Product Name</th>
				<tr>
			</thead>
			<tbody>
				<tr ng-repeat="rs in products">
					<td>{{ rs.id }}</td>
					<td>{{ rs.productname }}</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>
<script src="angular.js"></script>
</body>
</html>
angular.js
//angular.js
var app = angular.module('appselect', []);
app.controller('selectController', function($scope, $http){
	$scope.fetch = function(){
		$http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data) 
            $scope.products = data.data;  
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.add = function(){
    	console.log($scope.newProduct);
		$http({
            method: 'POST',
            url: 'add.php',
			data: $scope.newProduct
        }).then(function (data){
            console.log(data) 
    		$scope.newProduct = '';
	        $scope.fetch();
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
});
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$output = array();
	$sql = "SELECT * FROM products";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
add.php
//add.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$data = json_decode(file_get_contents("php://input"));

	$productname = $data->productname;

	$sql = "INSERT INTO products (productname) VALUES ('$productname')";
	$conn->query($sql);
	
?>

AngularJS Simple Like and Dislike

AngularJS Simple Like and Dislike

Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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

Bootstrap Icons
https://icons.getbootstrap.com/#install
CDN : https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css
index.html
//index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" name = "viewport" content = "width-device=width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src = "js/script.js"></script>
</head>
<body ng-app = "likedislike" ng-controller = "likedislikeCTR">
	<nav class = "navbar navbar-default">
		<div class = "container-fluid">
			<a class = "navbar-brand" href =  "#">Cairocoders</a>
		</div>
	</nav>
	<div class = "row">
		<div class = "col-md-3"></div>
		<div class = "col-md-6">
			<h3 class = "text-primary">AngularJS Simple Like and Dislike</h3>
			<hr style = "border-top:1px dotted #000;"/>
			<br /><br />
			<table class = "table table-bordered">
				<thead>
					<tr>
						<th>Programming Language</th>
						<th>Like</th>
						<th>Dislike</th>
						<th>Action</th>
					</tr>
				</thead>
				<tbody>
					<tr ng-repeat="pLang in pLangs">
						<td>{{pLang.name}}</td>
						<td>{{pLang.Likes}}</td>
						<td>{{pLang.Dislikes}}</td>
						<td><center><button class = "btn btn-primary" ng-click =  "incrementUp(pLang)"><i class="bi bi-hand-thumbs-up"></i></button> | <button class = "btn btn-danger" ng-click = "decrementDown(pLang)"><i class="bi bi-hand-thumbs-down"></i></button></center></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class = "col-md-3"></div>
	</div>
</body>		
</html>
script.js
//script.js
var myApp = angular.module("likedislike", [])
	.controller("likedislikeCTR" , function($scope){
									
	var pLangs =[
		{name: "Javascript", Likes: 0, Dislikes: 0},
		{name: "Python", Likes: 0, Dislikes: 0},
		{name: "Java", Likes: 0, Dislikes: 0},
		{name: "PHP", Likes: 0, Dislikes: 0},
		{name: "Swift", Likes: 0, Dislikes: 0}
	];					

	$scope.pLangs = pLangs;
	
	$scope.incrementUp = function(pLang){
		pLang.Likes++;
	}
	
	$scope.decrementDown = function(pLang){
		pLang.Dislikes++;
	}
});	

Friday, January 28, 2022

AngularJS Multiple File Upload with PHP MySQLi

AngularJS Multiple File Upload with 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

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `uploads` (`id`, `file_name`) VALUES
(1, '1643355908_01.jpg'),
(2, '1643426291_02.jpg'),
(3, '1643426291_13532763_1267843279894447_3651828689419392719_n.jpg'),
(4, '1643426291_13882562_10153788775718730_5796830824454484119_n.jpg');

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

ALTER TABLE `uploads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS Multiple File Upload with PHP MySQLi</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/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="uploadmultiple" ng-controller="uploadCTR" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Multiple File Upload with PHP MySQLi</h1>
	<div class="row">
		<div class="col-3">
			<h3 class="text-center">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>
			<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 class="col-9">
			<div class="row">
			<div class="col-md-4" ng-repeat="rs in images" style="margin-bottom:10px;">
				<img ng-src="upload/{{ rs.file_name }}" width="100%" height="250px" class="thumbnail">
			</div>
			</div>
		</div>
	</div>
</div>
<script src="angular.js"></script>
</body>
</html>
angular.js
//angular.js
var app = angular.module('uploadmultiple', []);
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('uploadCTR', function($scope, $http){

	$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},
        }).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.');
        });
	}

	$scope.fetch = function(){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data) 
			$scope.images = 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);
?>

Vue CLI Install Create project and run

Vue CLI Install Create project and run

Download and install Node.js and NPM Package in your system

https://nodejs.org/en/download/
https://docs.npmjs.com/cli/v8/configuring-npm/install

check the node and npm is installed

node js:
$ node -v

version of npm
$ npm -v

Check Vue JS Verison
$ vue --version
$ vue -V

Install the Vue CLI 

https://cli.vuejs.org/

https://cli.vuejs.org/guide/installation.html

$ npm install -g @vue/cli

create a project in Vue Cli 

$ vue create my-vue-app

cd my-vue-app
$ npm run serve


Thursday, January 27, 2022

SwiftUI Spinner Loading/Waiting Activity

SwiftUI Spinner Loading/Waiting Activity

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State var show = false
    
    var body: some View {

        ZStack {
            if self.show {
                GeometryReader { geometry in
                    Loader()
                        .position(x: geometry.size.width / 2, y: geometry.size.height / 2)
                }.background(Color.black.opacity(0.45).edgesIgnoringSafeArea(.all))
                    .onTapGesture {
                        self.show.toggle()
                    }
                
            }else {
                Button(action: {
                    self.show.toggle()
                }) {
                    Text("Show Custom Indicator")
                }
            }
        }
        

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct Loader : View {
    
    @State var animate = false
    
    var body: some View {
        VStack {
            Circle()
                .trim(from: 0, to: 0.8)
                .stroke(AngularGradient(gradient: .init(colors: [.red,.orange]), center: .center), style: StrokeStyle(lineWidth: 8, lineCap: .round))
                .frame(width: 45, height: 45)
                .rotationEffect(.init(degrees: self.animate ? 360 : 0))
                .animation(Animation.linear(duration: 0.7).repeatForever(autoreverses: false))
                .padding(.top, 10)
            
            Text("Please Wait...").padding()
        }
        .background(Color.white)
        .cornerRadius(15)
        .onAppear {
            self.animate.toggle()
        }
    }
}

SwiftUI User Notification

SwiftUI User Notification

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders 
//

import SwiftUI

struct ContentView: View {

    var body: some View {
        NavigationView {
            ZStack {
                Button(action: {
                    self.send()
                }) {
                    Text("Send Notification")
                }.navigationBarTitle("Home")
            }
        }
    }
    
    func send() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("All set!")
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
        
        let content = UNMutableNotificationContent()
        content.title = "Message"
        content.subtitle = "New Tutorial from cairocoders!!"
        content.sound = UNNotificationSound.default
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

AngularJS Search Suggestion with PHP MySQLi

AngularJS Search Suggestion with 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


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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;

Angular-ui-router
https://ui-router.github.io/ng1/
index.html
//index.html
<!DOCTYPE html>
<html ng-app="searchsuggestion">
<head>
<title>AngularJS Search Suggestion with PHP/MySQLi</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/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://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js"></script>
<style type="text/css">
		.sug-list{
		    background-color: #4CAF50; 
		    border: 1px solid #FFFFFF; 
		    color: #FFFFFF; 
		    padding: 10px 24px; 
		    cursor: pointer; 
		    width: 100%;
		    display: block;
			margin-top:1px;
		}
		.sug-list:not(:last-child) {
    		border-bottom: none; 
		}
		.sug-list a {
			text-decoration:none;
			color: #FFFFFF;
		}
		.no-sug{
		    background-color: #4CAF50; 
		    border: 1px solid #FFFFFF; 
		    color: #FFFFFF; 
		    padding: 10px 24px;  
		    width: 100%;
		    display: block;
			margin-top:1px;
		}
	</style>  
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">AngularJS Search Suggestion with PHP MySQLi</h1>
	<div ui-view></div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = angular.module('searchsuggestion', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    
    $stateProvider
        
        .state('home', {
            url: '/home',
            templateUrl: 'home.html',
            controller: 'homeCtrl'
        })
        
        .state('member', {
            url: '/member/{member:json}',
            params: {member: null},
            templateUrl: 'member.html',
            controller: 'memberCtrl'
        })  
});

app.controller('homeCtrl', function($scope, $http) {
    $scope.hasMember = false;
    $scope.noMember = false;

    $scope.search = function(){
        if($scope.keyword == ''){
           $scope.hasMember = false;
            $scope.noMember = false;
        }
        else{
			$http({
				method: 'POST',
				url: 'search.php',
				data: { keyword: $scope.keyword }
			}).then(function (data){
				console.log(data)
                if(data.data.length > 0){
                    $scope.members = data.data;
                    $scope.hasMember = true;
                    $scope.noMember = false;
                }
                else{
                    $scope.noMember = true;
                    $scope.hasMember = false;
                }     
			},function (error){
				console.log(error, 'can not get data.');
			});
        }
    }
});

app.controller('memberCtrl', function($scope, $stateParams) {
    $scope.details = $stateParams.member;
});
home.html
//home.html
<div class="row">
	<div class="col-12" style="padding:20px;">
		<input type="text" class="form-control" ng-model="keyword" ng-keyup="search()" placeholder="Search for Firstname, Lastname or Address">	
		<div ng-repeat="member in members" ng-show="hasMember" class="sug-list">
			<a ui-sref="member({member: member})">{{ member.firstname + ' ' + member.lastname }}</a>
		</div>
		<div ng-show="noMember" class="no-sug">
			No Suggestion Found
		</div>
	</div>
</div>
search.php
//search.php
<?php
	$conn = new mysqli("localhost", "root", "", "testingdb");

	$out = array();

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

	$keyword = $data->keyword;

	if(empty($keyword)){
		$out = '';
	}
	else{

		$sql = "SELECT * FROM members WHERE firstname LIKE '%$keyword%' OR lastname LIKE '%$keyword%' OR address LIKE '%$keyword%'";
		$query = $conn->query($sql);

		while($row=$query->fetch_array()){
			$out[] = $row;
		}
	}

	echo json_encode($out);
?>
member.html
//member.html
<h2 class="text-center">Member Details</h1>
<div class="col-sm-4 col-sm-offset-4">
<h3>Member ID: {{ details.id }}</h3>
<h3>Firstname: {{ details.firstname }}</h3>
<h3>Lastname: {{ details.lastname }}</h3>
<h3>Address: {{ details.address }}</h3>

<button type="button" ui-sref="home" class="btn btn-primary">Back</button>

Wednesday, January 26, 2022

AngularJS Delete Multiple Rows with PHP MySQLi

AngularJS Delete Multiple Rows with 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


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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;

index.html
//index.html
<!DOCTYPE html>
<html lang="en" ng-app="deletemultiplerow">
<head>
<meta charset="utf-8">
<title>AngularJS Delete Multiple Rows with PHP MySQLi</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="MemberCtr" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Delete Multiple Rows with PHP MySQLi</h1>
    <div class="row">
		<div class="col-10 col-md-offset-2">
			<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-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-warning"></i> {{ errorMessage }}
			</div>
			
			<button class="btn btn-danger" ng-click="deleteAll()">Delete</button>
			
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                    	<th><input type="checkbox" ng-model="checkAll" ng-change="toggleAll()"></th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Address</th>
                   </tr>
                </thead>
				<tbody>
					<tr ng-repeat="member in members">
						<td><input type="checkbox" ng-model="member.Selected" ng-change="toggleOne()"></td>
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
						<td>{{ member.address }}</td>
					</tr>
				</tbody>
			</table>
			</div>
		</div>
	</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
//script.js
var app = angular.module('deletemultiplerow', []);
app.controller('MemberCtr',function($scope, $http){
    $scope.success = false;
    $scope.error = false;

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

    $scope.toggleAll = function(){
        for (var i = 0; i < $scope.members.length; i++) {
            $scope.members[i].Selected = $scope.checkAll;
        }
    };

    $scope.toggleOne = function(){
        $scope.checkAll = true;
        for (var i = 0; i < $scope.members.length; i++) {
            if (!$scope.members[i].Selected) {
                $scope.checkAll = false;
                break;
            }
        };
    };
        
    $scope.deleteAll = function(){
        checkedId = [];
        for (var i = 0; i < $scope.members.length; i++) {
            if ($scope.members[i].Selected) {
                checkedId.push($scope.members[i].id);
            }
        }
		$http({
            method: 'POST',
            url: 'delete.php',
			data:checkedId,
        }).then(function (data){
            console.log(data);
            if(data.data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.errorMessage = data.data.message;
                $scope.checkAll = false;
            }
            else{
                $scope.success = true;
                $scope.error = false;
                $scope.successMessage = data.data.message;
                $scope.fetch();
                $scope.checkAll = false;
            }     
        },function (error){
            console.log(error, 'can not get data.');
        });
		
    }

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

});
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$output = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
delete.php
//delete.php
<?php
  $conn = new mysqli('localhost', 'root', '', 'testingdb');

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

  $out = array('error' => false);
  
  foreach ($data as $key => $value) {
    $sql = "DELETE FROM members WHERE id = '".$value."'";
    $query = $conn->query($sql);
  }

  if($query){
    $out['message'] = "Member(s) deleted Successfully";
  }
  else{
    $out['error'] = true;
    $out['message'] = "Something went wrong. Cannot delete Member(s)";
  }

  echo json_encode($out);
?>

Tuesday, January 25, 2022

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql


https://bootstrap-vue.org/

https://bootstrap-vue.org/docs/components/modal#modals

https://vuejs.org/v2/guide/

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

https://github.com/axios/axios

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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;
crud.html
//crud.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</title>
</head>
<body>
<div class="container" id="vuejscrudapp">
	<div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</h1>
          <hr>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
          <!-- Add Records -->
        <div>
            <b-button id="show-btn" @click="showModal('my-modal')">Add Records</b-button>
 
            <b-modal ref="my-modal" hide-footer title="Add Records">
              <div>
                <form action="" @submit.prevent="onSubmit">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Add Records</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
            </b-modal>
        </div>
 
        <!-- Update Record -->
        <div>
            <b-modal ref="my-modal1" hide-footer title="Update Record">
              <div>
                <form action="" @submit.prevent="onUpdate">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="edit_id">
                    <input type="text" v-model="edit_firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="edit_lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="edit_address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Update Record</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal1')">Close Me</b-button>
            </b-modal>
          </div>
		  
        </div>
	</div>
	  
    <div class="row">
        <div class="col-md-12">
          <table class="table table-striped table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Address</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, i) in records" :key="record.id">
                <td>{{i + 1}}</td>
                <td>{{record.firstname}}</td>
                <td>{{record.lastname}}</td>
                <td>{{record.address}}</td>
                <td>
                  <button @click="deleteRecord(record.id)" class="btn btn-sm btn-outline-danger">Delete</button>
                  <button @click="editRecord(record.id)" class="btn btn-sm btn-outline-info">Edit</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
    </div>
</div>
 
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- BootstrapVue js -->
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    var app = new Vue({
        el: '#vuejscrudapp',
        data: {
			firstname: '',
			lastname: '',
			address: '',
			records: [],
			edit_id: '',
			edit_firstname: '',
			edit_lastname: '',
			edit_address: ''
        },
 
        methods: {
			showModal(id) {
				this.$refs[id].show()
			},
			hideModal(id) {
				this.$refs[id].hide()
			},
 
			onSubmit(){
				if (this.firstname !== '' && this.lastname !== '' && this.address !== '') {
					var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/insert", 
						{ firstname : this.firstname, lastname : this.lastname, address : this.address}, config
					)
					.then(res => {
						console.log(res)
						alert('New record Successfully added')
						this.firstname = ''
						this.lastname = ''
						this.address = ''
		 
						app.hideModal('my-modal')
						app.getRecords()
					})
					.catch(err => {
						console.log(err)
					})
				}else{
				  alert('empty')
				}
			},
 
			getRecords(){
				axios({
				  url: 'http://localhost:5000/',
				  method: 'get'
				})
				.then(res => {
				  console.log(res)
				  this.records = res.data.members
				})
				.catch(err => {
				  console.log(err)
				})
			},
 
			editRecord(id){
				axios.get("http://127.0.0.1:5000/edit/" + id)
				.then(res => {
					console.log(res.data)
				    this.edit_id = res.data.editmember['id']
				    this.edit_firstname = res.data.editmember['firstname']
				    this.edit_lastname = res.data.editmember['lastname']
				    this.edit_address = res.data.editmember['address']
					app.showModal('my-modal1')
				})
				.catch(err => {
				  console.log(err)
				})
			},
			
			onUpdate(){
				if (this.edit_firstname !== '' && this.edit_lastname !== '' && this.edit_address !== '' && this.edit_id !== '') {

				    var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/update", 
						{ edit_id : this.edit_id, edit_firstname : this.edit_firstname, edit_lastname : this.edit_lastname, edit_address : this.edit_address}, config
					)
					.then(res => {
						console.log(res)
						alert('record update');
		 
						this.edit_firstname = '';
						this.edit_lastname = '';
						this.edit_address = '';
						this.edit_id = '';
		 
						app.hideModal('my-modal1');
						app.getRecords();
					})
					  .catch(err => {
						console.log(err)
					})
	 
				}else{
				  alert('empty')
				}
			},
			
			deleteRecord(id){
				if (window.confirm('Delete this record')) {
					axios.get("http://127.0.0.1:5000/delete/" + id)
					.then(res => {
						console.log(res)
						alert('delete successfully')
						app.getRecords();
					})
					.catch(err => {
						console.log(err)
					})
				}
			},
		
        },
		  
        mounted: function(){
          this.getRecords()
        }
    })
</script>
</body>   
</html>
app.py
//app.py
from flask import Flask, jsonify, request
from flask_cors import CORS
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql

MEMBERS = [
    {
        'id': '1',
        'firstname': 'cairocoders',
        'lastname': 'Ednalan',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'firstname': 'clydey',
        'lastname': 'Ednalan',
        'address': 'Angles city'
    }
]
# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
    
mysql = MySQL()
   
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')

@app.route('/members', methods=['GET'])
def all_members():
    return jsonify({
        'status': 'success',
        'members': MEMBERS
    })

@app.route('/')
def home():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute("SELECT * from members order by id")
        userslist = cursor.fetchall()
        return jsonify({
            'status': 'success',
            'members': userslist
        })
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

@app.route('/insert', methods=['GET', 'POST'])
def insert():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        firstname = post_data.get('firstname')
        lastname = post_data.get('lastname')
        address = post_data.get('address')

        print(firstname)
        print(lastname)

        sql = "INSERT INTO members(firstname,lastname,address) VALUES(%s, %s, %s)"
        data = (firstname, lastname, address)
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(sql, data)
        conn.commit()

        response_object['message'] = "Successfully Added"
    return jsonify(response_object)

@app.route('/edit/<string:id>', methods=['GET', 'POST'])
def edit(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    print(id)
    cursor.execute("SELECT * FROM members WHERE id = %s", [id])
    row = cursor.fetchone() 

    return jsonify({
        'status': 'success',
        'editmember': row
    })

@app.route('/update', methods=['GET', 'POST'])
def update():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        edit_id = post_data.get('edit_id')
        edit_firstname = post_data.get('edit_firstname')
        edit_lastname = post_data.get('edit_lastname')
        edit_address = post_data.get('edit_address')

        print(edit_firstname)
        print(edit_lastname)

        cursor.execute ("UPDATE members SET firstname=%s, lastname=%s, address=%s WHERE id=%s",(edit_firstname, edit_lastname, edit_address, edit_id))
        conn.commit()
        cursor.close()

        response_object['message'] = "Successfully Updated"
    return jsonify(response_object)

@app.route('/delete/<string:id>', methods=['GET', 'POST'])
def delete(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
  
    response_object = {'status': 'success'}

    cursor.execute("DELETE FROM members WHERE id = %s", [id])
    conn.commit()
    cursor.close()
    response_object['message'] = "Successfully Deleted"
    return jsonify(response_object)

if __name__ == '__main__':
    app.run()

Sunday, January 23, 2022

Python Flask Vue.js fetchAll Data from Mysql Database

Python Flask Vue.js fetchAll Data from Mysql Database

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

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

https://github.com/axios/axios


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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;


index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Python Flask Vue.js fetchAll Data from Mysql Database</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
  <div class="container" id="fetchAlldiv">
   <br />
   <h3 align="center">Python Flask Vue.js fetchAll Data from Mysql Database</h3>
   <br />

   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
       <h3 class="panel-title"> Member List</h3>
     </div>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
          <table class="table table-bordered table-striped">
           <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Address</th>
            <th>Edit</th>
            <th>Delete</th>
           </tr>
           <tr v-for="rs in allData">
			  <td>{{ rs.firstname }}</td>
              <td>{{ rs.lastname }}</td>
              <td>{{ rs.address }}</td>
            <td><button type="button" name="edit" class="btn btn-primary btn-xs edit">Edit</button></td>
            <td><button type="button" name="delete" class="btn btn-danger btn-xs delete">Delete</button></td>
           </tr>
          </table>
        </div>
    </div>
   </div>
</div>
<script>
var application = new Vue({
    el:'#fetchAlldiv',
    data:{
        allData:'',
    },
    methods:{
        fetchAllData:function(){ //show records
           axios.get('http://localhost:5000/')
		   .then(function(response){
				console.log(response);
				application.allData = response.data.members;
           });
        }
    }, 
    created:function(){
      this.fetchAllData();
    }
});
</script>
</body>
</html>
app.py
//app.py
from flask import Flask, jsonify
from flask_cors import CORS
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
    
mysql = MySQL()
   
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

@app.route('/')
def home():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute("SELECT * from members order by id")
        userslist = cursor.fetchall()
        return jsonify({
            'status': 'success',
            'members': userslist
        })
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

if __name__ == '__main__':
    app.run()

Saturday, January 22, 2022

AngularJS Search and Sort with PHP MySQLi

AngularJS Search and Sort with 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

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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh'),
(74, 'test1', 'test1lastname', 'olongapo');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=75;
index.php
//index.php
<!DOCTYPE html>
<html lang="en" ng-app="searchandsort">
<head>
<meta charset="utf-8">
<title>AngularJS Search and Sort with PHP MySQLi</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>
<style type="text/css">
.gray{
    color:gray;
}
</style>
</head>
<body ng-controller="Controllersearchsort">
<div class="container">
    <h1 class="page-header text-center">AngularJS Search and Sort with PHP MySQLi</h1>
    <div class="row">
		<div class="col-12 col-md-offset-2">
			<div class="row">
				<div class="col-md-4 col-md-offset-8">
					<input type="text" ng-model="search" class="form-control" placeholder="Search">
				</div>
			</div>
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                       	<th ng-click="sort('id')">ID
	                       	<span class="pull-right">
	                       		<i class="fa fa-sort gray" ng-show="sortKey!='id'"></i>
	                       		<i class="fa fa-sort" ng-show="sortKey=='id'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
	                       	</span>
                       	</th>
                        <th ng-click="sort('firstname')">First Name
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='firstname'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='firstname'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                        </th>
                        <th ng-click="sort('lastname')">Last Name
	                        <span class="pull-right">
	                       		<i class="fa fa-sort gray" ng-show="sortKey!='lastname'"></i>
	                       		<i class="fa fa-sort" ng-show="sortKey=='lastname'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
	                       	</span>
                        </th>
                        <th ng-click="sort('address')">Address
                        	<span class="pull-right">
                       			<i class="fa fa-sort gray" ng-show="sortKey!='address'"></i>
                       			<i class="fa fa-sort" ng-show="sortKey=='address'" ng-class="{'fa fa-sort-asc':reverse,'fa fa-sort-desc':!reverse}"></i>
                       		</span>
                       	</th>
                    </tr>
                </thead>
				<tbody>
					<tr ng-repeat="member in members|orderBy:sortKey:reverse|filter:search">
						<td>{{ member.id }}</td>
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
						<td>{{ member.address }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
//script.js
var app = angular.module('searchandsort', []);
app.controller('Controllersearchsort',function($scope, $http){
    $http({
        method: 'GET',
        url: 'fetch.php',
    }).then(function (data){
        console.log(data)
        $scope.members = data.data;      
    },function (error){
        console.log(error, 'can not get data.');
    });

    $scope.sort = function(keyname){
        $scope.sortKey = keyname;   
        $scope.reverse = !$scope.reverse;
    }
});
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	$output = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>

Thursday, January 20, 2022

AngularJS Upload with PHP MySQLi

AngularJS Upload with 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

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `uploads` (`id`, `file_name`) VALUES
(1, '1642658228_01.jpg'),
(2, '1642668773_02.jpg'),
(3, '1642669093_14813122_10154009777823730_1000226838_o.jpg');

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

ALTER TABLE `uploads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS Upload with PHP MySQLi</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="uploadphpmysql" ng-controller="uploadcontroller" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Upload with PHP MySQLi</h1>
	<div class="row" style="margin-top:60px;">
		<div class="col-4">
			<h3 class="text-center">Upload File</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files">
			<hr>
			<button class="btn btn-primary" ng-click="upload()"><span class="glyphicon glyphicon-download-alt"></span> Upload</button>
			
			<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 class="col-8">
			<div class="row">
			<div class="col-4" ng-repeat="image in images">
				<img ng-src="upload/{{ image.file_name }}" width="100%" height="250px" class="thumbnail">
			</div>
			</div>
		</div>
	</div>
</div>
<script src="appupload.js"></script>
</body>
</html>
appupload.js
//appupload.js
var app = angular.module('uploadphpmysql', []);
app.directive('fileInput', function($parse){
	return{
		restrict: 'A', //'A' - only matches attribute name
		link:function($scope, element, attrs){
			element.on('change', function(e){
				var files = e.target.files;
				$parse(attrs.fileInput).assign($scope, element[0].files);
				$scope.$apply();
			});
		}
	}
});
app.controller('uploadcontroller', function($scope, $http){
	$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}
        }).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.');
        });
	},

	$scope.fetch = function(){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.images = 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)){
		$newFilename = time() . "_" . $_FILES['file']['name'];
		$path = 'upload/' . $newFilename;
		if(move_uploaded_file($_FILES['file']['tmp_name'], $path)){
			$sql = "INSERT INTO uploads (file_name) VALUES ('$newFilename')";
			$query=$conn->query($sql);
			if($query){
				$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);
?>

Wednesday, January 19, 2022

AngularJS Form Validation

AngularJS Form Validation

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" ng-app="formvalidation">
<head>
<meta charset="utf-8">
<title>AngularJS Form Validation</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>
<style type="text/css">
.errortext{
    color:red;
}
</style>
</head>
<body ng-controller="cntform">
<h1 class="page-header text-center">AngularJS Form Validation</h1>
<div class="signup-form">
    <form role="form" name="myForm" novalidate>
		<h2>Register</h2>
		<p class="hint-text">Create your account. It's free and only takes a minute.</p>
		<div class="form-group">
        	<input type="text" class="form-control" name="username" placeholder="Username" ng-minlength="10" ng-maxlength="30" ng-pattern="/^[a-zA-Z0-9_]*$/" ng-model="user.username" required autofocus>
			<div class="errortext" ng-show="myForm.username.$dirty && myForm.username.$invalid">
			    <span ng-show="myForm.username.$error.required">Username is required</span>
			    <span ng-show="myForm.username.$error.minlength">Username must contain atleast 10 characters</span>
			    <span ng-show="myForm.username.$error.maxlength">Username should not be greater than 30 characters</span>
			    <span ng-show="myForm.username.$error.pattern && !myForm.username.$error.minlength && !myForm.username.$error.maxlength">Only letters, numbers and underscore allowed</span>
			</div>
        </div>
        <div class="form-group">
			<div class="row">
				<div class="col-xs-6">
			        <input type="text" class="form-control" name="firstname" placeholder="Firstname" ng-model="user.firstname" required>
			        <div class="errortext" ng-show="myForm.firstname.$dirty && myForm.firstname.$invalid">
			            <span ng-show="myForm.firstname.$error.required">Firstname is required</span>
			        </div>
				</div>
				<div class="col-xs-6">
			        <input  type="text" class="form-control" name="lastname" placeholder="Lastname" ng-model="user.lastname" required>
			        <div class="errortext" ng-show="myForm.lastname.$dirty && myForm.lastname.$invalid">
			            <span ng-show="myForm.lastname.$error.required">Lastname is required</span>
			        </div>
				</div>
			</div>        	
        </div>
        <div class="form-group">
			<input  type="email" class="form-control" name="email" placeholder="Email" ng-model="user.email" required>
			<div class="errortext" ng-show="myForm.email.$dirty && myForm.email.$invalid">
			    <span ng-show="myForm.email.$error.required">Email is required</span>
			    <span ng-show="myForm.email.$error.email">Invalid email format</span>
			</div>
        </div>        
		<div class="form-group">
			<input type="url" class="form-control" name="url" placeholder="Website" ng-model="user.website" required>
			<div class="errortext" ng-show="myForm.url.$dirty && myForm.url.$invalid">
			    <span ng-show="myForm.url.$error.required">Website is required</span>
			    <span ng-show="myForm.url.$error.url">Input a valid website</span>
			</div>
        </div>
		<div class="form-group">
			<input type="password" class="form-control" name="password" placeholder="Password" ng-model="user.password" required>
			<div class="errortext" ng-show="myForm.password.$dirty && myForm.password.$invalid">
			    <span ng-show="myForm.password.$error.required">Password is required</span>
			</div>
        </div>
		<div class="form-group">
			<input type="password" class="form-control" name="repassword" placeholder="Re-type Password" ng-model="user.repassword" required>
			<div class="errortext" ng-show="myForm.repassword.$dirty && myForm.repassword.$invalid || myForm.repassword.$dirty && user.repassword != user.password">
			    <span ng-show="myForm.repassword.$error.required">Re-type password is required</span>
			    <span ng-show="!myForm.repassword.$error.required && user.repassword != user.password">Password did not match</span>
			</div>
        </div>        
        <div class="form-group">
			<label class="checkbox-inline"><input type="checkbox" required="required"> I accept the <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label>
		</div>
		<div class="form-group">
			<button type="button" class="btn btn-success btn-lg btn-block" ng-disabled="myForm.$invalid || user.repassword != user.password" ng-click="submit()"><span class="glyphicon glyphicon-check"></span> Register Now</button>
        </div>
		
		<div class="alert alert-success text-center" ng-show="valid">
			<button type="button" class="close" ng-click="close()"><span aria-hidden="true">×</span></button>
			<span class="glyphicon glyphicon-check"></span> Form Validated
		</div>
		
    </form>
	<div class="text-center">Already have an account? <a href="#">Sign in</a></div>
</div>
<script>
var app = angular.module('formvalidation', []);
app.controller('cntform', function($scope){
	$scope.valid = false;
	$scope.submit = function(){
		$scope.valid = true;
	}
	$scope.close = function(){
		$scope.valid = false;
	}
});
</script>
<style>
	body {
		color: #fff;
		background: #63738a;
		font-family: 'Roboto', sans-serif;
	}
    .form-control{
		height: 40px;
		box-shadow: none;
		color: #969fa4;
	}
	.form-control:focus{
		border-color: #5cb85c;
	}
    .form-control, .btn{        
        border-radius: 3px;
    }
	.signup-form{
		width: 400px;
		margin: 0 auto;
		padding: 30px 0;
	}
	.signup-form h2{
		color: #636363;
        margin: 0 0 15px;
		position: relative;
		text-align: center;
    }
	.signup-form h2:before, .signup-form h2:after{
		content: "";
		height: 2px;
		width: 30%;
		background: #d4d4d4;
		position: absolute;
		top: 50%;
		z-index: 2;
	}	
	.signup-form h2:before{
		left: 0;
	}
	.signup-form h2:after{
		right: 0;
	}
    .signup-form .hint-text{
		color: #999;
		margin-bottom: 30px;
		text-align: center;
	}
    .signup-form form{
		color: #999;
		border-radius: 3px;
    	margin-bottom: 15px;
        background: #f2f3f7;
        box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
        padding: 30px;
    }
	.signup-form .form-group{
		margin-bottom: 20px;
	}
	.signup-form input[type="checkbox"]{
		margin-top: 3px;
	}
	.signup-form .btn{        
        font-size: 16px;
        font-weight: bold;		
		min-width: 140px;
        outline: none !important;
    }
	.signup-form .row div:first-child{
		padding-right: 10px;
	}
	.signup-form .row div:last-child{
		padding-left: 10px;
	}    	
    .signup-form a{
		color: #fff;
		text-decoration: underline;
	}
    .signup-form a:hover{
		text-decoration: none;
	}
	.signup-form form a{
		color: #5cb85c;
		text-decoration: none;
	}	
	.signup-form form a:hover{
		text-decoration: underline;
	}  
</style>
</body>
</html>

Tuesday, January 18, 2022

AngularJS Inline Edit with PHP MySQLi

AngularJS Inline Edit with PHP MySQLi

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

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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh'),
(74, 'test1', 'test1lastname', 'olongapo');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=75;
index.html
//index.html
<!DOCTYPE html>
<html lang="en" ng-app="appinline">
<head>
<meta charset="utf-8">
<title>AngularJS Inline Edit with PHP MySQLi</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="inlineCrt" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Inline Edit with PHP MySQLi</h1>
    <div class="row">
		<div class="col-md-10 col-md-offset-1">
			<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> {{ message }}
			</div>
			<div class="alert alert-danger text-center" ng-show="error">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<i class="fa fa-warning"></i> {{ message }}
			</div>
			
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Address</th>
                        <th>Action</th>
                   </tr>
                </thead>
				<tbody>
					<tr ng-repeat="data in members" ng-include="getTemplate(data)">
					</tr>
				</tbody>
			</table>
			<script type="text/ng-template" id="normal">
        		<td>{{data.firstname}}</td> 
				<td>{{data.lastname}}</td>
				<td>{{data.address}}</td>
				<td><button type="button" ng-click="edit(data)" class="btn btn-success"><span class="glyphicon glyphicon-pencil"></span> Edit</button></td>
    		</script>
    		<script type="text/ng-template" id="edit">
        		<td><input type="text" class="form-control"  ng-model="editmember.firstname"></td>
				<td><input type="text" class="form-control"  ng-model="editmember.lastname"></td>
				<td><input type="text" class="form-control" ng-model="editmember.address"></td>
				<td>
					<button type="button" ng-click="save(editmember)" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
            		<button type="button" ng-click="reset()" class="btn btn-default"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
				</td>
    		</script>
		</div>
	</div>
</div>
<script>
var app = angular.module('appinline', []);
app.controller('inlineCrt', function($scope, $http){
    $scope.success = false;
    $scope.error = false;
    $scope.editMode = false;

    $scope.editmember = {};

    $scope.getTemplate = function (data) {
        if (data.id === $scope.editmember.id) return 'edit';
        else return 'normal';
    };

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

    $scope.edit = function(data){
        $scope.editmember = angular.copy(data);  
    }

    $scope.save = function(editmember){
		$http({
            method: 'POST',
            url: 'save.php',
			data:$scope.editmember,
        }).then(function (data){
            console.log(data);
            if(data.data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.message = data.data.message;
            }
            else{
                $scope.fetch();
                $scope.reset();
                $scope.success = true;
                $scope.error = false;
                $scope.message = data.data.message;
            }    
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

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

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

});
</script>
</body>
</html>
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	
	$output = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
save.php
//save.php
<?php
  $conn = new mysqli('localhost', 'root', '', 'testingdb');

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

  $out = array('error' => false);
  
  $id = $data->id;
  $firstname = $data->firstname;
  $lastname = $data->lastname;
  $address = $data->address;

  $sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";
  $query = $conn->query($sql);

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

  echo json_encode($out);
?>

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

Related Post