article

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

Thursday, March 17, 2022

Angular.js PHP OOP CRUD (Create Read Update and Delete)

Angular.js PHP OOP 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

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

CREATE TABLE `tblmembers` (
  `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;

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

ALTER TABLE `tblmembers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8"> 
	<title>Angular.js PHP OOP CRUD (Create Read Update and Delete)</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container">
	<h1 class="page-header">Angular.js PHP OOP CRUD (Create Read Update and Delete) </h1>
	<div class="row">
		<div ng-app="mem_app" ng-controller="controller" ng-init="showdata()">
			<div class="row">
				<form ng-submit="myFunc()">
					<h3>Member Form</h3>
					<hr>
					<div class="form-group">
				    	<label for="firstname">Firstname</label>
				    	<input type="text" class="form-control" id="firstname" name="firstname" ng-model="firstname" placeholder="Enter Firstname">
				  	</div>
				  	<div class="form-group">
				    	<label for="lastname">Lastname</label>
				    	<input type="text" class="form-control" id="lastname" name="lastname" ng-model="lastname" placeholder="Enter Lastname">
				  	</div>
					<div class="form-group">
				    	<label for="address">Address</label>
				    	<input type="text" class="form-control" id="address" name="address" ng-model="address" placeholder="Enter Address">
				  	</div>
				  	<hr>
					
				  	<button type="submit" class="{{btnClass}}" ng-click="insert()"><i class="{{icon}}"></i>  {{btnName}}</button>
				</form>
			</div>
			<div class="row">
				<h3>Member List</h3>
				<table class="table table-bordered table-striped">
					<thead>
						<th>Firstname</th>
						<th>Lastname</th>
						<th>Address</th>
						<th>Action</th>
					</thead>
					<tbody>
						<tr ng-repeat="mem in member">
							<input type="hidden" value="{{mem.id}}">
							<td>{{mem.firstname}}</td>
							<td>{{mem.lastname}}</td>
							<td>{{mem.address}}</td>
							<td>
								<button class="btn btn-success" ng-click="update(mem.id, mem.firstname, mem.lastname, mem.address)"><i class="bi bi-pencil"></i> Edit</button> || 
								<button class="btn btn-danger" ng-click="delete(mem.id)"><i class="bi bi-trash"></i> Delete</button>
							</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = angular.module("mem_app", []);
app.controller("controller", function($scope, $http) {
    $scope.btnName = "Save";
    $scope.icon = "bi bi-save";
    $scope.btnClass = "btn btn-primary";
    $scope.insert = function() {
        if ($scope.firstname == null) {
            alert("Please input Firstname");
        } 
        else if ($scope.lastname == null) {
            alert("Please input Lastname");
        }  
        else {
			$http({
				method: 'POST',
				url: 'action.php',
				data: { firstname: $scope.firstname, lastname: $scope.lastname, address: $scope.address, btnName: $scope.btnName, id: $scope.id }
			}).then(function (data){
				console.log(data)  
                alert(data.data);
                $scope.firstname = null;
                $scope.lastname = null;
                $scope.address = null;
                $scope.btnName = "Save";
                $scope.icon = "bi bi-save";
                $scope.btnClass = "btn btn-primary";
                $scope.showdata();
			},function (error){
				console.log(error, 'can not get data.');
			});
        }
    }
    $scope.showdata = function() {
		$http({
            method: 'GET',
            url: 'fetch.php'
        }).then(function (data){
            console.log(data)  
            $scope.member = data.data;  
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
    $scope.update = function(id, firstname, lastname, address) {
        $scope.id = id;
        $scope.firstname = firstname;
        $scope.lastname = lastname;
        $scope.address = address;
        $scope.icon = "bi bi-send-check";
        $scope.btnClass = "btn btn-success";
        $scope.btnName = "Update";
    }
    $scope.delete= function(id) { 
        if (confirm("Are you sure you want to delete member?")) {
			$http({
				method: 'POST',
				url: 'delete.php',
				data:{'id':id}
			}).then(function (data){
				console.log(data)  
				alert(data.data);
				$scope.showdata();
			},function (error){
				console.log(error, 'can not get data.');
			});
        } else {
            return false;
        }
    }
    $scope.enter = function(keyEvent) {
        if (keyEvent.which === 13){
            insert();
        }
    }
});
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 tblmembers"); 
	if ($query->num_rows > 0) {
	    while ($row = $query->fetch_array()) {
	        $output[] = $row;
	    }
	    echo json_encode($output);
	}
?>
action.php
//action.php
<?php
    include('conn.php');
    $info = json_decode(file_get_contents("php://input"));
    $firstname = mysqli_real_escape_string($conn, $info->firstname);
    $lastname = mysqli_real_escape_string($conn, $info->lastname);
    $address = mysqli_real_escape_string($conn, $info->address);
    $btn_name = $info->btnName;
	$output = array(); 
	
    if ($btn_name == "Save") {
        if ($conn->query("insert into tblmembers (firstname, lastname, address) values ('$firstname', '$lastname', '$address')")) {
			$output[] = "Member Added Successfully";
        } else {
			$output[] = "Failed";
        }
    }
    if ($btn_name == "Update") {
        $id  = $info->id;
        if ($conn->query("update tblmembers set firstname='$firstname', lastname='$lastname', address='$address' where id='$id'")) {
			$output[] = "Member Updated Successfully";
        } else {
		   $output[] = "Failed";
        }
    }
echo json_encode($output);
?>
delete.php
//delete.php
<?php
	include('conn.php');
	$data = json_decode(file_get_contents("php://input"));

	$id = $data->id;
	if ($conn->query("delete from tblmembers where id='$id'")) {
	    echo 'Member Deleted Successfully';
	} else {
	    echo 'Failed';
	}
?>

Tuesday, February 8, 2022

AngularJS PHP Mysql Add Dynamically Remove Input Fields

AngularJS PHP Mysql Add Dynamically Remove Input Fields

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

CREATE TABLE `tblprogramming` (
  `id` int(11) NOT NULL,
  `username` varchar(150) NOT NULL,
  `title` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `tblprogramming` (`id`, `username`, `title`) VALUES
(1, 'cairocoders', 'python, python flask, python django, python tkinter');

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

ALTER TABLE `tblprogramming`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Add Dynamically Remove Input Fields</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<h3 align="center">AngularJS PHP Mysql Add Dynamically Remove Input Fields </h3>
<br />
<div ng-app="appdynamicaddremove" ng-controller="CTRdynamicaddremove" class="container" style="width:600px;" ng-init="fetchData()">
   
	<div class="alert alert-success alert-dismissible" ng-show="success" >
		<a href="#" class="close" aria-label="close">×</a>
		{{successMessage}}
	</div>

	<div class="alert alert-danger alert-dismissible" ng-show="error" >
		<a href="#" class="close" aria-label="close">×</a>
		{{errorMessage}}
	</div>

	<form method="post" ng-submit="submitForm()">
		<div class="form-group">
			User Name : Cairocoders
		</div>
		<fieldset ng-repeat="row in rows">
			<div class="form-group">
				<label>Enter Your Programming Skill</label>
				<div class="row">
				   <div class="col-md-9">
						<input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
				   </div>
				   <div class="col-md-3">
						<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><i class="bi bi-dash-square"></i></button>
				   </div>
				</div>
			</div>
		</fieldset>
		<div class="form-group">
		 <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><i class="bi bi-plus-square"></i> Add</button>
		 <input type="submit" name="submit" class="btn btn-info" value="Save" />
		</div>
	</form>

   <div class="table-responsive">
		<table class="table table-bordered table-striped">
			<tr>
			  <th>Programming Languages</th>
			</tr>
			<tr ng-repeat="rs in skills">
			  <td>{{rs.title}}</td>
			</tr>
		</table>
   </div>
</div>
<script>
var app = angular.module('appdynamicaddremove', []);
app.controller('CTRdynamicaddremove', function($scope, $http){

	$scope.success = false;
	$scope.error = false;

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

	$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];

	$scope.addRow = function(){
		var id = $scope.rows.length + 1;
		$scope.rows.push({'id':'dynamic'+id});
	};

	$scope.removeRow = function(row){
		var index = $scope.rows.indexOf(row);
		$scope.rows.splice(index, 1);
	};

	$scope.formData = {};

	$scope.submitForm = function(){
		$http({
			method: 'POST',
			url: 'insert.php',
			data:$scope.formData
		}).then(function (data){
			console.log(data)  
			   if(data.data.error != '')
			   {
				$scope.success = false;
				$scope.error = true;
				$scope.errorMessage = data.data.error;
			   }
			   else
			   {
				$scope.success = true;
				$scope.error = false;
				$scope.successMessage = data.data.message;
				$scope.formData = {};
				$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
				$scope.fetchData();
			   }
		},function (error){
			console.log(error, 'can not post data.');
		});
	};

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

$query = "SELECT * FROM tblprogramming ORDER BY id";
$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
$connect = new PDO('mysql:host=localhost;dbname=testingdb', 'root', '');

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

$error = '';
$message = '';
$validation_error = '';
$programming_languages = '';

if(empty($form_data->skill)){
	$error[] = 'Programming Language is Required';
}else{
	 foreach($form_data->skill as $language)
	 {
		$programming_languages .= $language . ', ';
	 }
	 $programming_languages = substr($programming_languages, 0, -2);
}

$data = array(
	':programming_languages' => $programming_languages
);

if(empty($error)) {
	$query = "
	INSERT INTO tblprogramming 
	 (username, title) VALUES 
	 ('cairocoders', :programming_languages)
	 ";
	 $statement = $connect->prepare($query);
	 if($statement->execute($data))
	 {
		$message = 'Data Inserted';
	 }
}else{
	$validation_error = implode(", ", $error);
}

$output = array(
	 'error'  => $validation_error,
	 'message' => $message
);
echo json_encode($output);
?>

AngularJS PHP Mysql Dynamic Dropdown List

AngularJS PHP Mysql Dynamic Dropdown List


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 `countries` (
  `id` int(6) NOT NULL,
  `value` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `countries` (`id`, `value`) VALUES
(1, 'Afghanistan'),
(171, 'Philippines'),
(227, 'United States of America');

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

ALTER TABLE `countries`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=228;
  
CREATE TABLE `state` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `state` (`id`, `name`, `country_id`) VALUES
(1, 'ARMM', 171),
(2, 'Bicol', 171),
(3, 'Central Luzon', 171),
(4, 'Central Mindanao', 171),
(5, 'Alabama', 227),
(6, 'Alaska', 227),
(7, 'Arizona', 227),
(8, 'California', 227),
(9, 'Florida', 227);

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

ALTER TABLE `state`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
index.html
//index.html
<!DOCTYPE html>  
<html>  
<head>  
<title>AngularJS PHP Mysql Dynamic Dropdown List</title>  
<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/4.0.0/css/bootstrap.min.css" />  
</head>  
<body>  
<div class="container" style="width:650px;">  
    <h3 align="center">AngularJS PHP Mysql Dynamic Dropdown List</h3>  
    <br />  
    <div ng-app="appdynamicdropdown" ng-controller="CTRdynamicdropdown" ng-init="loadCountry()">  
        <select name="country" ng-model="country" class="form-control" ng-change="loadState()">  
            <option value="">Select Country</option>  
            <option ng-repeat="country in countries" value="{{country.id}}">{{country.value}}</option>  
        </select>  
        <br />  
        <select name="state" ng-model="state" class="form-control">  
            <option value="">Select State</option>  
            <option ng-repeat="state in states" value="{{state.id}}">  
                {{state.name}}  
            </option>  
        </select>  
    </div>  
</div> 
<script>  
var app = angular.module("appdynamicdropdown",[]);  
app.controller("CTRdynamicdropdown", function($scope, $http){  
      $scope.loadCountry = function(){  
		$http({
			method: 'GET',
			url: 'load_country.php'
		}).then(function (data){
			console.log(data)  
			$scope.countries = data.data;  
		},function (error){
			console.log(error, 'can not get data.');
		});
      }  
	  
      $scope.loadState = function(){  
		$http({
			method: 'POST',
			url: 'load_state.php',
			data: { country_id: $scope.country }
		}).then(function (data){
			console.log(data)  
			$scope.states = data.data;   
		},function (error){
			console.log(error, 'can not post data.');
		}); 
      }  
 });  
</script> 		   
</body>  
</html>   
load_country.php
//load_country.php
<?php   
 $connect = mysqli_connect("localhost", "root", "", "testingdb");  
 $output = array();  
 $query = "SELECT * FROM countries ORDER BY value ASC";  
 $result = mysqli_query($connect, $query);  
 while($row = mysqli_fetch_array($result))  
 {  
    $output[] = $row;  
 }  
 echo json_encode($output);  
?>  
load_state.php
//load_state.php
<?php   
 $connect = mysqli_connect("localhost", "root", "", "testingdb");  
 $output = array();  
 $data = json_decode(file_get_contents("php://input"));  
 $query = "SELECT * FROM state WHERE country_id='".$data->country_id."' ORDER BY name ASC";  
 $result = mysqli_query($connect, $query);  
 while($row = mysqli_fetch_array($result))  
 {  
    $output[] = $row;  
 }  
 echo json_encode($output);  
?>

AngularJS Autocomplete Textbox

AngularJS Autocomplete Textbox

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>  
<head>  
<title>AngularJS Autocomplete Textbox</title>  
<link rel="stylesheet" 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>  
<div class="container" style="width:500px;margin-top:20px;">  
    <h3 align="center">AngularJS Autocomplete Textbox</h3>  
    <div ng-app="appautocomplete" ng-controller="CTRautocomplete">  
        <label>Enter Country Name</label>  
        <input type="text" name="country" id="country" ng-model="country" ng-keyup="complete(country)" class="form-control" />  
        <ul class="list-group" ng-model="hidethis" ng-hide="hidethis">  
            <li class="list-group-item" ng-repeat="countrydata in filterCountry" ng-click="fillTextbox(countrydata)">{{countrydata}}</li>  
        </ul>  
    </div>  
</div>  
<script>  
 var app = angular.module("appautocomplete",[]);  
 app.controller("CTRautocomplete", function($scope){  
      $scope.countryList = [  
           "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"  
      ];  
      $scope.complete = function(string){  
           $scope.hidethis = false;  
           var output = [];  
           angular.forEach($scope.countryList, function(country){  
                if(country.toLowerCase().indexOf(string.toLowerCase()) >= 0)  
                {  
                     output.push(country);  
                }  
           });  
           $scope.filterCountry = output;  
      }  
      $scope.fillTextbox = function(string){  
           $scope.country = string;  
           $scope.hidethis = true;  
      }  
 });  
</script>
<style>  
li{  
   cursor:pointer;  
}  
li:hover{  
    background-color:#f9f9f9;  
}  
</style> 
</body>  
</html>  

AngularJS PHP Mysql Submit Form Data

AngularJS PHP Mysql Submit Form Data

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;

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS PHP Mysql Submit Form Data</title>
<link rel="stylesheet" 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>
<div class="container" style="width:750px;">
    <h3 align="center">AngularJS PHP Mysql Submit Form Data</h3>
    <br /><br />
    <div ng-app="myapp" ng-controller="formcontroller">
    <form name="userForm" ng-submit="insertData()">
		<label class="text-success" ng-show="successInsert">{{successInsert}}</label>
		<div class="form-group">
			<label>First Name <span class="text-danger">*</span></label>
			<input type="text" name="first_name" ng-model="insert.first_name" class="form-control" />
			<span class="text-danger" ng-show="errorFirstname">{{errorFirstname}}</span>
		</div>
		<div class="form-group">
			<label>Last Name <span class="text-danger">*</span></label>
			<input type="text" name="last_name" ng-model="insert.last_name" class="form-control" />
			<span class="text-danger" ng-show="errorLastname">{{errorLastname}}</span>
		</div>
		<div class="form-group">
			<label>Address <span class="text-danger">*</span></label>
			<input type="text" name="address" ng-model="insert.address" class="form-control" />
			<span class="text-danger" ng-show="erroraddress">{{erroraddress}}</span>
		</div>
		<br />
		<div class="form-group">
			<input type="submit" name="insert" class="btn btn-info" value="Insert"/>
		</div>
    </form>
    </div>
</div>
  
<script>
var application = angular.module("myapp", []);
application.controller("formcontroller", function($scope, $http){
	$scope.insert = {};
	$scope.insertData = function(){
		$http({
			method: 'POST',
			url: 'insert.php',
			data:$scope.insert,
		}).then(function (data){
			console.log(data) 
			   if(data.data.error)
			   {
				$scope.errorFirstname = data.data.error.first_name;
				$scope.errorLastname = data.data.error.last_name;
				$scope.erroraddress = data.data.error.address;
				$scope.successInsert = null;
			   }
			   else
			   {
				$scope.insert = null;
				$scope.errorFirstname = null;
				$scope.errorLastname = null;
				$scope.erroraddress = null;
				$scope.successInsert = data.data.message;
			   } 
		},function (error){
			console.log(error, 'can not post data.');
		});
	}
});
</script>
</body>
</html>
insert.php
//insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testingdb");
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->first_name))
{
	$error["first_name"] = "First Name is required";
}

if(empty($form_data->last_name))
{
	$error["last_name"] = "Last Name is required";
}

if(!empty($error))
{
	$data["error"] = $error;
}
else
{
	$first_name = mysqli_real_escape_string($connect, $form_data->first_name); 
	$last_name = mysqli_real_escape_string($connect, $form_data->last_name);
	$address = mysqli_real_escape_string($connect, $form_data->address);
	$query = "
	  INSERT INTO members(firstname, lastname, address) VALUES ('$first_name', '$last_name', '$address')
	";
	if(mysqli_query($connect, $query))
	{
	  $data["message"] = "Data Inserted...";
	}
}
echo json_encode($data);
?>

AngularJS Jquery Datatables with PHP Mysql

AngularJS Jquery Datatables with PHP Mysql

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

Jquery
https://jquery.com/download/

Other CDNs jsDelivr CDN : https://www.jsdelivr.com/package/npm/jquery 
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

https://datatables.net/
CDN version 1.11.4

Angular DataTables
https://github.com/l-lin/angular-datatables


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Jquery Datatables with PHP Mysql</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="angular-datatables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css">
</head>
<body>
<div ng-app="Appdatatables" ng-controller="CTRdatatables" class="container">
	<br />
	<h3 align="center">AngularJS Jquery Datatables with PHP Mysql</h3>
	<br />
	<table datatable="ng" dt-options="vm.dtOptions" class="table table-striped table-bordered">
		<thead>
			<tr>
				<th>Sr</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Address</th>
			</tr>
		</thead>
		<tbody>
			<tr ng-repeat="rs in members">
				<td>{{ $index + 1 }}</td>
				<td>{{ rs.firstname }}</td>
				<td>{{ rs.lastname }}</td>
				<td>{{ rs.address }}</td>
			</tr>
		</tbody>
	</table>
	<br />
	<br />
</div>
<script>
var app = angular.module('Appdatatables', ['datatables']);
app.controller('CTRdatatables', 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.');
    });
});
</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);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
	$data[] = $row;
}
echo json_encode($data);
?>

AngularJS Show Password

AngularJS Show Password

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

https://icons.getbootstrap.com/
CDN : https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

https://getbootstrap.com/docs/5.1/getting-started/introduction/
index.html
//index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AngularJS Show Password</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div id="login">
<div class="container" ng-app="appshowpassword" ng-controller="CTR_showpass">
   <br />
   <h2 align="center">AngularJS Show Password</h2><br />

    <div id="login-row" class="row justify-content-center align-items-center">
	<div id="login-column" class="col-md-6">
		<div id="login-box" class="col-md-12">
			<div class="panel-heading">
				<h3 class="panel-title">Login</h3>
			</div>
			<div class="panel-body">
				<div class="form-group">
				  <label>Enter Email</label>
				  <input type="text" name="email" class="form-control input-lg" ng-model="email_field" placeholder="Enter Email">
				</div>
				<div class="form-group">
					<label>Enter Password</label> 
					<div class="input-group">
						<input type="{{inputType}}" name="password" class="form-control input-lg" ng-model="password_field" placeholder="Enter Password" />
						<span class="{{showHideClass}}" ng-click="showPassword()" style="cursor:pointer"></span>
					</div>
				</div>
				<div class="form-group">
                    <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br>
                    <input type="submit" name="submit" class="btn btn-info btn-lg" value="submit">
                </div>
			</div>
		</div>
   </div>
   </div>
</div>
</div>
<script>
var app = angular.module('appshowpassword', []);
app.controller('CTR_showpass', function($scope){

	$scope.inputType = 'password';
	$scope.showHideClass = 'input-group-text bi bi-eye-slash-fill';

	$scope.showPassword = function(){
		if($scope.password_field != null) {
			if($scope.inputType == 'password')
			{
				 $scope.inputType = 'text';
				 $scope.showHideClass = 'input-group-text bi bi-eye-fill'; 
			}
			else
			{
				 $scope.inputType = 'password';
				 $scope.showHideClass = 'input-group-text bi bi-eye-slash-fill';
			}
		}
	};

});
</script>
<style>
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
  height: 100vh;
}
#login .container #login-row #login-column #login-box {
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
  padding: 20px;
}
#login .container #login-row #login-column #login-box #login-form {
  padding: 20px;
}
</style>
</body>
</html>

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

Thursday, January 27, 2022

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

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

Related Post