Friday 22 April 2022

Add dynamic rows in html table with Add, Edit, Delete feature in PHP and MySQLi

dynamic-table.php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title> Dynamic Table in PhP</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,300,600,700" rel="stylesheet" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link href="../css/bootstrap.min.css?ver=3.3.5" rel="stylesheet" />
<link href="../css/font-awesome.min.css?ver=4.6.3" rel="stylesheet" />
<link rel="stylesheet" href="css/dataTables.bootstrap.min.css" />
</head>
<body>
<script src="../js/jquery-3.5.1.min.js"></script>
<script src="../js/jquery.dataTables.min.js"></script>
<script src="../js/bootstrap.min.js?ver=3.3.5"></script>
<script src="../js/jquery-ui.js"></script>
<script>
      $(document).ready(function(){
       $("#fromdate").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd/mm/yy'                          
             
            });
        $("#todate").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd/mm/yy'                          
             
            });
  var employeeData = $('#employeeList').DataTable({
"processing":true,
"serverSide":true,
"bFilter":false,
"bSort" : false ,
"bPaginate": false,
"bInfo" : false,
"order":[],
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listEmployee'},
dataType:"json"
}
});
$('#addEmployee').click(function(){
$('#employeeModal').modal('show');
$('#employeeForm')[0].reset();
$('.modal-title').html("<i class='fa fa-plus'></i> Add Employment Details");
$('#action').val('addEmployee');
$('#save').val('Add');
});
$("#employeeList").on('click', '.update', function(){
var empId = $(this).attr("id");
var action = 'getEmployee';
$.ajax({
url:'action.php',
method:"POST",
data:{empId:empId, action:action},
dataType:"json",
success:function(data){
$('#employeeModal').modal('show');
$('#empId').val(data.id);
$('#post').val(data.post);
$('#company').val(data.company);
$('#type').val(data.type);
$('#fromdate').val(data.fromdate);
$('#todate').val(data.todate);
$('#scale').val(data.scale);
$('#gross').val(data.gross);
$('.modal-title').html("<i class='fa fa-plus'></i> Edit Employee");
$('#action').val('updateEmployee');
$('#save').val('Save');
}
})
});
$("#employeeModal").on('submit','#employeeForm', function(event){
event.preventDefault();
$('#save').attr('disabled','disabled');
var formData = $(this).serialize();
$.ajax({
url:"action.php",
method:"POST",
data:formData,
success:function(data){
$('#employeeForm')[0].reset();
$('#employeeModal').modal('hide');
$('#save').attr('disabled', false);
employeeData.ajax.reload();
}
})
});
$("#employeeList").on('click', '.delete', function(){
var empId = $(this).attr("id");
var action = "empDelete";
if(confirm("Are you sure you want to delete this employee?")) {
$.ajax({
url:"action.php",
method:"POST",
data:{empId:empId, action:action},
success:function(data) {
employeeData.ajax.reload();
}
})
} else {
return false;
}
});
});
</script>
<div id="content" class="site-content">
<div class="container">
<div class="row">
<div class="col-md-12 padding-bottom-20">
<div class="row row-margin">
<div class="col-md-12">
<div class="container">
<div id="payment" style="display: block;">
<div style="overflow-x: auto;">
<div class="col-lg-10 col-md-10 col-sm-9 col-xs-12">   
<div class="panel-heading">
<div class="row">
<div class="col-md-10">
<h3 class="panel-title"></h3>
</div>
<div class="col-md-2" align="right">
<button type="button" name="add" id="addEmployee" class="btn btn-success btn-xs" style="font-size: 15px;padding: 10%;">Add New Row</button>
</div>
</div>
</div>
<table id="employeeList" class="table table-bordered table-striped" style="width:100%;">
        <thead>
<tr>
<th>Post held</th>
<th>Department/ Institute/ Company</th>
<th>Permanent/ Temporary/ Contract</th>
<th>From Date</th>
<th>To Date</th>
<th>Scale of pay</th>
<th>Gross Amount</th>
<th></th>
<th></th>
</tr>
</table>
</div>
<div id="employeeModal" class="modal fade">
    <div class="modal-dialog">
    <form method="post" id="employeeForm">
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Edit Employment Details</h4>
    </div>
    <div class="modal-body">
<div class="form-group"
<label for="post" class="control-label">Post held</label>
<input type="text" class="form-control" id="post" name="post" placeholder="Post held" required>
</div>
<div class="form-group">
<label for="company" class="control-label">Department/ Institute/ Company</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Department/ Institute/ Company">
</div>    
<div class="form-group">
<label for="type" class="control-label">Permanent/ Temporary/ Contract</label>
<input type="text" class="form-control"  id="type" name="type" placeholder="Permanent/ Temporary/ Contract" required="required">
</div>  
<div class="form-group">
<label for="fromdate" class="control-label">From Date [dd/mm/yyyy]</label>
<input type="text" class="form-control"  id="fromdate" name="fromdate" placeholder="From Date" autocomplete="off" readonly="readonly" required="required" ></textarea>
</div>
<div class="form-group">
<label for="todate" class="control-label">To Date [dd/mm/yyyy]</label>
<input type="text" class="form-control" id="todate" name="todate" placeholder="To Date" autocomplete="off" readonly="readonly" required="required" >
</div>
<div class="form-group">
<label for="scale" class="control-label">Scale of pay</label>
<input type="text" class="form-control" id="scale" name="scale" placeholder="Scale of pay" required="required" >
</div>
<div class="form-group">
<label for="gross" class="control-label">Gross Amount</label>
<input type="text" class="form-control" id="gross" name="gross" placeholder="Gross Amount" required="required" >
</div>
    </div>
    <div class="modal-footer">
    <input type="hidden" name="empId" id="empId" />
    <input type="hidden" name="userid" id="userid" value="12"/>   
    <input type="hidden" name="action" id="action" value="" />
    <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
    </div>
    </form>
    </div>
    </div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- .col-md-9 --></div>
<!-- .row --></div>
<!-- .container --></div>

action.php

<?php
include('Employee.php');
$emp = new Employee();
if(!empty($_POST['action']) && $_POST['action'] == 'listEmployee') {
$emp->employeeList();
}
if(!empty($_POST['action']) && $_POST['action'] == 'addEmployee') {
$emp->addEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'getEmployee') {
$emp->getEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'updateEmployee') {
$emp->updateEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'empDelete') {
$emp->deleteEmployee();
}
?>

Config.php

<?php
class dbConfig {
    protected $serverName;
    protected $userName;
    protected $password;
    protected $dbName;
    function dbConfig() {
        $this -> serverName = 'localhost';
        $this -> userName = 'root';
        $this -> password = "";
        $this -> dbName = "employee";
    }
}
?>

Employee.php

<?php require('config.php'); class Employee extends Dbconfig { protected $hostName; protected $userName; protected $password; protected $dbName; private $empTable = 'employment'; private $dbConnect = false; public function __construct(){ if(!$this->dbConnect){ $database = new dbConfig(); $this -> hostName = $database -> serverName; $this -> userName = $database -> userName; $this -> password = $database ->password; $this -> dbName = $database -> dbName; $conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName); if($conn->connect_error){ die("Error failed to connect to MySQL: " . $conn->connect_error); } else{ $this->dbConnect = $conn; } } } public function employeeList(){ $sqlQuery = "SELECT * FROM ".$this->empTable." "; $result = mysqli_query($this->dbConnect, $sqlQuery); $employeeData = array(); while( $employee = mysqli_fetch_assoc($result) ) { $empRows = array(); $empRows[] = $employee['post']; $empRows[] = $employee['company']; $empRows[] = $employee['type']; $empRows[] = $employee['fromdate']; $empRows[] = $employee['todate']; $empRows[] = $employee['scale']; $empRows[] = $employee['gross']; $empRows[] = '<button type="button" name="update" id="'.$employee["id"].'" class="btn btn-warning btn-xs update">Update</button>'; $empRows[] = '<button type="button" name="delete" id="'.$employee["id"].'" class="btn btn-danger btn-xs delete" >Delete</button>'; $employeeData[] = $empRows; } $output = array( "draw" => intval($_POST["draw"]), "data" => $employeeData ); echo json_encode($output); } public function getEmployee(){ if($_POST["empId"]) { $sqlQuery = " SELECT * FROM ".$this->empTable." WHERE id = '".$_POST["empId"]."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); echo json_encode($row); } } public function updateEmployee(){ if($_POST['empId']) { $updateQuery = "UPDATE ".$this->empTable." SET userid = '".$_POST["userid"]."', post = '".$_POST["post"]."', company = '".$_POST["company"]."', type = '".$_POST["type"]."', fromdate = '".$_POST["fromdate"]."' , todate = '".$_POST["todate"]."' , scale = '".$_POST["scale"]."', gross = '".$_POST["gross"]."' WHERE id ='".$_POST["empId"]."'"; $isUpdated = mysqli_query($this->dbConnect, $updateQuery); } } public function addEmployee(){ $insertQuery = "INSERT INTO ".$this->empTable." (userid, post, company, type, fromdate, todate,scale, gross) VALUES ('".$_POST["userid"]."','".$_POST["post"]."', '".$_POST["company"]."', '".$_POST["type"]."', '".$_POST["fromdate"]."', '".$_POST["todate"]."', '".$_POST["scale"]."', '".$_POST["gross"]."')"; $isUpdated = mysqli_query($this->dbConnect, $insertQuery); } public function deleteEmployee(){ if($_POST["empId"]) { $sqlDelete = " DELETE FROM ".$this->empTable." WHERE id = '".$_POST["empId"]."'"; mysqli_query($this->dbConnect, $sqlDelete); } } } ?>

employee.sql

CREATE TABLE `employment` (
  `id` int(10) NOT NULL,
  `userid` int(10) DEFAULT NULL,
  `post` varchar(100) DEFAULT NULL,
  `company` varchar(100) DEFAULT NULL,
  `type` varchar(25) DEFAULT NULL,
  `fromdate` varchar(25) DEFAULT NULL,
  `todate` varchar(25) DEFAULT NULL,
  `scale` varchar(50) DEFAULT NULL,
  `gross` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


Thursday 21 April 2022

Unified Process (UP) Best Practices

  • Get high risk and high value requirements first
  • Constant user feedback and engagement
  • Early cohesive core architecture
  • Test early, often, and realistically
  • Apply use cases where needed
  • Do some visual modeling with UML
  • Manage requirements and scope creep
  • Manage change requests and configuration

How to persist the selected value of the select box after form submit?

 <?php
if ($_POST['submit']) {
    if ($_POST['srf'] != "") {
        $srf = $_POST['srf'];
    } else {
        $srfErr = "This field is required.";
    }
}
?>
<form method="post">
<select name="srf" id="srf" class="form-control">
<option value="">Select</option>
<option <?php if (isset($srf) && $srf=="1") echo "selected";?>>1</option>
<option <?php if (isset($srf) && $srf=="2") echo "selected";?>>2</option>
<option <?php if (isset($srf) && $srf=="3") echo "selected";?>>3</option>
</select> <?php if($srfErr!= ""){ ?>
        <p><b><?php echo $srfErr;  ?></b></p>
</div>
    <?php }?>
<input type="submit" name="submit" value="submit" />
</form>

Unified Process Phases

Inception

  • Inception is not a requirements phase; rather a feasibility phase, where just enough investigation is done to support a decision to continue or stop. –
  • The life-cycle objectives of the project are stated, so that the needs of every stakeholder are considered. Scope and boundary conditions, acceptance criteria and some requirements are established.
  • Approximate vision, business case, scope, vague estimates.

Inception - Activities

  •  Formulate the scope of the project: Needs of every stakeholder, scope, boundary conditions and acceptance criteria established.
  •  Plan and prepare the business case: Define risk mitigation strategy, develop an initial project plan and identify known cost, schedule, and profitability trade-offs.
  • Synthesize candidate architecture: Candidate architecture is picked from various potential architectures
  • Prepare the project environment

Inception - Exit criteria

  • An initial business case containing at least a clear formulation of the product vision - the core requirements - in terms of functionality, scope, performance, capacity, technology base.
  • Success criteria (example: revenue projection).
  • An initial risk assessment.
  • An estimate of the resources required to complete the elaboration phase.

Elaboration

  • An analysis is done to determine the risks, stability of vision of what the product is to become, stability of architecture and expenditure of resources. 
  • Refined vision, iterative implementation of core architecture, resolution of high risks, identification of most requirements and scope, more realistic estimates

Elaboration - Entry criteria

  • The products and artifacts described in the exit criteria of the previous phase. 
  • The plan approved by the project management, and funding authority, and the resources required for the elaboration phase have been allocated

Elaboration - Activities

  • Define the architecture: Project plan is defined. The process, infrastructure and development environment are described. 
  • Validate the architecture.  
  • Baseline the architecture: To provide a stable basis for the bulk of the design and implementation effort in the construction phase.

Elaboration - Exit criteria 
  • A detailed software development plan, with an updated risk assessment, a management plan, a staffing plan, a phase plan showing the number and contents of the iteration , an iteration plan, and a test plan
  • The development environment and other tools 
  • A baseline vision, in the form of a set of evaluation criteria for the final product.
  • A domain analysis model, sufficient to be able to call the corresponding architecture ‘complete’. 
  • An executable architecture baseline. 

Construction 

  • The Construction phase is a manufacturing process. It emphasizes managing resources and controlling operations to optimize costs, schedules and quality. This phase is broken into several iterations. 
  •  Iterative implementation of the remaining lower risk and easier elements, and preparation for deployment. 

Construction - Entry criteria 
  • The product and artifacts of the previous iteration. The iteration plan must state the iteration specific goals
  • Risks being mitigated during this iteration. 
  • Defects being fixed during the iteration. 

Construction - Activities 
  • Develop and test components: Components required satisfying the use cases, scenarios, and other functionality for the iteration are built. Unit and integration tests are done on Components. 
  • Manage resources and control process. 
  • Assess the iteration: Satisfaction of the goal of iteration is determined.

Construction - Exit Criteria 
  • The same products and artifacts, updated, plus
  • A release description document, which captures the results of an iteration 
  • Test cases and results of the tests conducted on the products
  • An iteration plan, detailing the next iteration 
  • Objective measurable evaluation criteria for assessing the results of the next iteration(s).  

Transition 

  • The transition phase is the phase where the product is put in the hands of its end users. It involves issues of marketing, packaging, installing, configuring, supporting the user. community, making corrections, etc. 
  • Beta tests, deployment. 

Transition - Entry criteria
  • The product and artifacts of the previous iteration, and in particular a software product sufficiently mature to be put into the hands of its users.

Transition - Activities  
  • Test the product deliverable in a customer environment. 
  • Fine tune the product based upon customer feedback 
  • Deliver the final product to the end user 
  • Finalize end-user support material.

Transition - Exit criteria 
  • An update of some of the previous documents, as necessary, the plan being replaced by a “post-mortem” analysis of the performance of the project relative to its original and revised success criteria; 
  • A brief inventory of the organization’s new assets as a result this cycle.  


Wednesday 20 April 2022

ER [Entity–relationship] Model

ER Model is a popular high-level (conceptual) data model. It is an approach to designing Semantic Conceptual schema of a Database. ER model allows us to describe the data involved in a real-world environment in terms of objects and their relationships, which are widely used in design of database. ER model provides preliminary concepts or idea about the data representation which is later modified to achieve final detailed design.

Important concepts/notions used in ER modeling are-

Entity 

It is an object in real-world or some idea or concept which can be distinguished from other objects.

Ex.: person, school, class, department, weather, salary, temperature etc.

Entity has independent existence. 

Entity type

Each entity belongs to an Entity type that defines the structure.

Entity Set 

It is a Collection of similar objects.

Attribute

Reflects a property of an object or entity. We have following types of attributes.

> Simple attribute

> Composite attribute

> Single valued attribute

> Multi-valued attribute

> Derived attribute

> Stored attribute

Key

Is an Attribute of an entity type whose value can uniquely identify an entity in a set.

Relationship

The association between entities is known as relationship.

Domain of an attribute

The set of possible values is known as domain of an attribute



Degree of a Relationship

Degree is the number of entity type participate in a relationship. 
If there are two entity types involved it is a binary relationship type
eg: Manager manages employee

If there are three entity types involved it is a ternary relationship type  

Cardinality of a relationship

Relationships are rarely one-to-one. 
For example, a manager usually manages more than one employee. This is described by the cardinality of the relationship, for which there are four possible categories. 



The Agile Principles

1. Satisfy the customer through early and continuous delivery of valuable software.

2. Welcome changing requirements, even late in development.

3. Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter time scale.

4. Business people and developers must work together daily throughout the project.

5. Build projects around motivated individuals.

6. The most efficient and effective method of conveying info. 

7. Working software is the primary measure of progress.

8. Agile processes promote sustainable development.

9. The sponsors, developers, and users should be able to maintain a constant pace indefinitely.

10. Continuous attention to technical excellence and good design enhances agility.

11. Simplicity – the art of maximizing the amount of work NOT done is essential.

12. The best architectures, requirements, and designs emerge from self- organizing teams.

13. At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.

Data Model

Data Model is a collection of concepts that can be used to describe the structure of the database. Structure means data types, relationships, constraints etc. DBMS allows a user to define the data to be stored in terms of a data model. 

1.  High-level data models 

2.  Low-level data models

3. Representational or Implementation data models 

High-level Data Models

Use set of concepts to describe the database, where the descriptions are close to user views. High-level data models are also known as conceptual models. In conceptual data modeling we use concepts like – entity, attributes, relationship etc. 

Low-level Data Models

Give details about how the data is stored in a computers (storage level details).

Representational/Implementation Data Models

This is in between high-level and low-level data models. Here we represent the concepts described in conceptual model using a specific structures like, networks, objects, tables, trees etc. Ex: Relational Model, NW Model, Hierarchical Model, Object Model, Object relational model etc. 

Relational Model

The central data description construct in this model is a relation, which can be thought of as a set of records. 

Schema

Description of data in terms of a data model is called a schema. A relation schema specifies the name of the relation, fields, type etc. 

eg:. Student (sid: string; name: string; age: integer) every row follows the schema of the relation.

The following are some important representational data models (DBMS Specific) 

1. Network Model

Though the basic structure is a record, the relationships are captured using links. The database can be seen as an arbitrary network of records connected by links. Ex.: GE’s Integrated Data store (IDS), in Early 1960s 

2. Hierarchical Model 

The records containing data are organized as a collection of trees. Ex.: IBMs IMS (Information Management System), in late 1960s 

3. Relational Model (early 1970s)

Data & relationships are captured as tables & keys. Ex.: Oracle, IBMs DB2, MySQL, Informix, Sybase, MS Access, Ingress, MySQL etc. The basic storage structure is a record. 

4. Object Data Model

Objects created through object–oriented programs can be stored in database. Ex.: Object Store 

5. Object Relational Model

Objects can be stores in tables. Ex.: Oracle, Informix