AngularJS PHP MySql
AngularJS PHP MySql
using a <script> tag. AngularJS extends HTML attributes with Directives. AngularJS Directives are HTML attributes with
a "ng" prefix (ng-init). If you are a beginner to AngularJS and looking for working example on AngularJs, this tutorial will
help you a lot. This tutorial will focus on CRUD (Create, Read, Update, and Delete) operations with AngularJS. We’ll do
the view, add, edit, and delete operations on a single page using AngularJS with PHP and MySQL.
In this example AngularJS CRUD application, we’ll implement the following functionalities.
Fetch the users data from the database using PHP & MySQL, and display the users data using AngularJS.
Add user data to the database using AngularJS, PHP, and MySQL.
Edit and update user data using AngularJS, PHP, and MySQL.
Delete user data from the database using AngularJS, PHP, and MySQL.
All the CRUD operations (view, add, edit, delete) will be done on a single page and without page reload or refresh. In
front-end part mainly AngularJs will handle the whole process and little jQuery will be used for some cases. In the back-
end, PHP will communicate with the database and provide the respective requested data to the front-end. PDO extension
and MySQL will help to connect with the database and database-related operations (select, insert, update, and delete).
Before you begin to AngularJS CRUD example, take a look at the files structure of the application which are going to
build.
For this example application, we’ll create a simple table (users) with some basic columns where users data would be
stored.
DB class handles all the operations related to the database using PHP PDO extension and MySQL. For example, connect
to the database, fetch, insert, update and delete the record from the database. You only need to change
the $dbHost, $dbUsername, $dbPassword, and $dbName variables value as per the database credentials.
<?php
class DB {
// Database credentials
private $dbHost = 'localhost';
private $dbUsername = 'root';
private $dbPassword = '';
private $dbName = 'angularphp';
public $db;
/*
* Connect to the database and return db connecction
*/
public function __construct(){
if(!isset($this->db)){
// Connect to the database
try{
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this-
>dbUsername, $this->dbPassword);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
}catch(PDOException $e){
die("Failed to connect with MySQL: " . $e->getMessage());
}
}
}
/*
* Returns rows from the database based on the conditions
* @param string name of the table
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
$query = $this->db->prepare($sql);
$query->execute();
/*
* Insert data into the database
* @param string name of the table
* @param array the data for inserting into the table
*/
public function insert($table,$data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
/*
* Update data into the database
* @param string name of the table
* @param array the data for updating into the table
* @param array where condition on updating data
*/
public function update($table,$data,$conditions){
if(!empty($data) && is_array($data)){
$colvalSet = '';
$whereSql = '';
$i = 0;
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$val = htmlspecialchars(strip_tags($val));
$colvalSet .= $pre.$key."='".$val."'";
&nnbsp; $i++;
}
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$sql = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
$query = $this->db->prepare($sql);
$update = $query->execute();
return $update?$query->rowCount():false;
}else{
return false;
}
}
/*
* Delete data from the database
* @param string name of the table
* @param array where condition on deleting data
*/
public function delete($table,$conditions){
$whereSql = '';
if(!empty($conditions)&& is_array($conditions)){
$whereSql .= ' WHERE ';
$i = 0;
foreach($conditions as $key => $value){
$pre = ($i > 0)?' AND ':'';
$whereSql .= $pre.$key." = '".$value."'";
$i++;
}
}
$sql = "DELETE FROM ".$table.$whereSql;
$delete = $this->db->exec($sql);
return $delete?$delete:false;
}
}
This file handles the requests coming from the HTML page by AngularJS and DB class helps to database related
operation. Based on the request, user data would read, add, update, delete from the database. Here the code is executed
based on the type. type would be four types, view, add, edit, and delete. The following operations can happen based on
the type.
view: fetch the records from the database, records and status message returns as JSON format.
add: insert the record in the database, inserted data and status message returns as JSON format.
edit: update the record in the database, status message returns as JSON format.
delete: delete the record from the database, status message returns as JSON format.
<?php
include 'DB.php';
$db = new DB();
$tblName = 'users';
if(isset($_REQUEST['type']) && !empty($_REQUEST['type'])){
$type = $_REQUEST['type'];
switch($type){
case "view":
$records = $db->getRows($tblName);
if($records){
$data['records'] = $db->getRows($tblName);
$data['status'] = 'OK';
}else{
$data['records'] = array();
$data['status'] = 'ERR';
}
echo json_encode($data);
break;
case "add":
if(!empty($_POST['data'])){
$userData = array(
'name' => $_POST['data']['name'],
'email' => $_POST['data']['email'],
'phone' => $_POST['data']['phone']
);
$insert = $db->insert($tblName,$userData);
if($insert){
$data['data'] = $insert;
$data['status'] = 'OK';
$data['msg'] = 'User data has been added successfully.';
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
echo json_encode($data);
break;
case "edit":
if(!empty($_POST['data'])){
$userData = array(
'name' => $_POST['data']['name'],
'email' => $_POST['data']['email'],
'phone' => $_POST['data']['phone']
);
$condition = array('id' => $_POST['data']['id']);
$update = $db->update($tblName,$userData,$condition);
if($update){
$data['status'] = 'OK';
$data['msg'] = 'User data has been updated successfully.';
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
echo json_encode($data);
break;
case "delete":
if(!empty($_POST['id'])){
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName,$condition);
if($delete){
$data['status'] = 'OK';
$data['msg'] = 'User data has been deleted successfully.';
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
}else{
$data['status'] = 'ERR';
$data['msg'] = 'Some problem occurred, please try again.';
}
echo json_encode($data);
break;
default:
echo '{"status":"INVALID"}';
}
}
This is the main view file, where all the users are listed with add, edit, and delete links. Also, the add, update, delete
Bootstrap CSS & JS library need to be included if you want to use Bootstrap table and form structure, otherwise, omit it.
At first, the application is defined using AngularJS module, then application controller is defined to control the application.
The following AngularJS functions are defined to handles the CRUD operations.
$scope.getRecords: The request is sent to the action.php file and store the response data into $scope.users.
$scope.saveUser: The user data is sent to the action.php file and insert or update the data in the database. At the time of
update, the updated data is stored in the respective index of $scope.users. At the time of insert, the inserted data to be
pushed to $scope.users. Once the operation is done, form data is reset and the status message is shown.
$scope.editUser: User data is stored in $scope.tempUserData, $scope.index is defined and the form is appear.
$scope.updateUser: $scope.saveUser is called with "edit" request.
$scope.deleteUser: The request is sent to the action.php file for delete data from the database. Based on the response,
user data is removed from the user list and status message is shown.
// define application
angular.module("crudApp", [])
.controller("userController", function($scope,$http){
$scope.users = [];
$scope.tempUserData = {};
// function to get records from the database
$scope.getRecords = function(){
$http.get('action.php', {
params:{
'type':'view'
}
}).success(function(response){
if(response.status == 'OK'){
$scope.users = response.records;
}
});
};
}
$scope.userForm.$setPristine();
$scope.tempUserData = {};
$('.formData').slideUp();
$scope.messageSuccess(response.msg);
}else{
$scope.messageError(response.msg);
}
});
};
HTML Code:
On page load, getRecords() function (defined by ng-init) is initialized which will fetch the records from the database.
AngularJS ng-repeat directive helps to list the users data and AngularJS expression ( {{ expression }}) is used to binds
ng-hide directive hides the HTML element based on the provided expression.
Expressions are used to bind the application data to HTML in AngularJS. AngularJS expressions are written inside the
<body ng-app="crudApp">
<div class="container" ng-controller="userController" ng-init="getRecords()">
<div class="row">
<div class="panel panel-default users-content">
<div class="panel-heading">Users <a href="javascript:void(0);" class="glyphicon glyphicon-plus"
onclick="$('.formData').slideToggle();"></a></div>
<div class="alert alert-danger none"><p></p></div>
<div class="alert alert-success none"><p></p></div>
<div class="panel-body none formData">
<form class="form" name="userForm">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="tempUserData.name"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ng-model="tempUserData.email"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" name="phone" ng-model="tempUserData.phone"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning"
onclick="$('.formData').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" ng-hide="tempUserData.id" ng-
click="addUser()">Add User</a>
<a href="javascript:void(0);" class="btn btn-success" ng-hide="!tempUserData.id" ng-
click="updateUser()">Update User</a>
</form>
</div>
<table class="table table-striped">
<tr>
<th width="5%">#</th>
<th width="20%">Name</th>
<th width="30%">Email</th>
<th width="20%">Phone</th>
<th width="14%">Created</th>
<th width="10%"></th>
</tr>
<tr ng-repeat="user in users | orderBy:'-created'">
<td>{{$index + 1}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
<td>{{user.created}}</td>
<td>
<a href="javascript:void(0);" class="glyphicon glyphicon-edit" ng-
click="editUser(user)"></a>
<a href="javascript:void(0);" class="glyphicon glyphicon-trash" ng-
click="deleteUser(user)"></a>
</td>
</tr>
</table>
</div>
</div>
</div>
</body>
CSS Code:
The following CSS is used for design purpose in our example application.
/* required style*/
.none{display: none;}
/* optional styles */
table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;width: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;cursor: pointer;}
.glyphicon-trash{margin-left: 10px;}
.alert{
width: 50%;
border-radius: 0;
margin-top: 10px;
margin-left: 10px;
}