article

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

Related Post