AngularJS CRUD Insert Update Delete with PHP and MySQL
Welcome on infinityknow.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to AngularJS CRUD Insert Update Delete with PHP and MySQL
In this post we will show you Best way to implement AngularJS CRUD Example | Create, Read, Update,Delete Using PHP, hear for How to AngularJS – Insert Update Delete using PHP and MySQL with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.
record_database Table Creation
[php]
CREATE TABLE `products` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`contact` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`isactive` enum(‘1′,’0’) COLLATE utf8_unicode_ci NOT NULL DEFAULT ‘1’,
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
[/php]
record_database Class (DB.php)
[php]
db)){
// Connect to the record_database
try{
$conn = new PDO(“myquery:host=”.$this->hostName.”;myDbName=”.$this->myDbName, $this->itemName, $this->itemPass);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
}catch(PDOException $e){
die(“Failed to connect with Myquery: ” . $e->getMessage());
}
}
}
public function selectRows($table,$livecondtion = array()){
$query = ‘SELECT ‘;
$query .= array_key_exists(“select”,$livecondtion)?$livecondtion[‘select’]:’*’;
$query .= ‘ FROM ‘.$table;
if(array_key_exists(“where”,$livecondtion)){
$query .= ‘ WHERE ‘;
$i = 0;
foreach($livecondtion[‘where’] as $key => $value){
$pre = ($i > 0)?’ AND ‘:”;
$query .= $pre.$key.” = ‘”.$value.”‘”;
$i++;
}
}
if(array_key_exists(“order_by”,$livecondtion)){
$query .= ‘ ORDER BY ‘.$livecondtion[‘order_by’];
}
if(array_key_exists(“start”,$livecondtion) && array_key_exists(“limit”,$livecondtion)){
$query .= ‘ LIMIT ‘.$livecondtion[‘start’].’,’.$livecondtion[‘limit’];
}elseif(!array_key_exists(“start”,$livecondtion) && array_key_exists(“limit”,$livecondtion)){
$query .= ‘ LIMIT ‘.$livecondtion[‘limit’];
}
$query = $this->db->prepare($query);
$query->execute();
if(array_key_exists(“return_type”,$livecondtion) && $livecondtion[‘return_type’] != ‘all’){
switch($livecondtion[‘return_type’]){
case ‘count’:
$record_data = $query->rowCount();
break;
case ‘single’:
$record_data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$record_data = ”;
}
}else{
if($query->rowCount() > 0){
$record_data = $query->fetchAll(PDO::FETCH_ASSOC);
}
}
return !empty($record_data)?$record_data:false;
}
/*
* Insert record_data into the record_database
* @param string name of the table
* @param array the record_data for inserting into the table
*/
public function insert($table,$record_data){
if(!empty($record_data) && is_array($record_data)){
$columns = ”;
$values = ”;
$i = 0;
if(!array_key_exists(‘created’,$record_data)){
$record_data[‘created’] = date(“Y-m-d H:i:s”);
}
if(!array_key_exists(‘modified’,$record_data)){
$record_data[‘modified’] = date(“Y-m-d H:i:s”);
}
$columnString = implode(‘,’, array_keys($record_data));
$valueString = “:”.implode(‘,:’, array_keys($record_data));
$query = “INSERT INTO “.$table.” (“.$columnString.”) VALUES (“.$valueString.”)”;
$query = $this->db->prepare($query);
foreach($record_data as $key=>$val){
$val = htmlspecialchars(strip_tags($val));
$query->bindValue(‘:’.$key, $val);
}
$insert = $query->execute();
if($insert){
$record_data[‘product_id’] = $this->db->lastInsertproduct_id();
return $record_data;
}else{
return false;
}
}else{
return false;
}
}
/*
* Update record_data into the record_database
* @param string name of the table
* @param array the record_data for updating into the table
* @param array where condition on updating record_data
*/
public function update($table,$record_data,$livecondtion){
if(!empty($record_data) && is_array($record_data)){
$oldcolmval = ”;
$newwherecondition = ”;
$i = 0;
if(!array_key_exists(‘modified’,$record_data)){
$record_data[‘modified’] = date(“Y-m-d H:i:s”);
}
foreach($record_data as $key=>$val){
$pre = ($i > 0)?’, ‘:”;
$val = htmlspecialchars(strip_tags($val));
$oldcolmval .= $pre.$key.”='”.$val.”‘”;
&nnbsp; $i++;
}
if(!empty($livecondtion)&& is_array($livecondtion)){
$newwherecondition .= ‘ WHERE ‘;
$i = 0;
foreach($livecondtion as $key => $value){
$pre = ($i > 0)?’ AND ‘:”;
$newwherecondition .= $pre.$key.” = ‘”.$value.”‘”;
$i++;
}
}
$query = “UPDATE “.$table.” SET “.$oldcolmval.$newwherecondition;
$query = $this->db->prepare($query);
$update = $query->execute();
return $update?$query->rowCount():false;
}else{
return false;
}
}
public function delete($table,$livecondtion){
$newwherecondition = ”;
if(!empty($livecondtion)&& is_array($livecondtion)){
$newwherecondition .= ‘ WHERE ‘;
$i = 0;
foreach($livecondtion as $key => $value){
$pre = ($i > 0)?’ AND ‘:”;
$newwherecondition .= $pre.$key.” = ‘”.$value.”‘”;
$i++;
}
}
$query = “DELETE FROM “.$table.$newwherecondition;
$delete = $this->db->exec($query);
return $delete?$delete:false;
}
}
[/php]
mainpage.php (fetch, insert, update, and delete records)
[php]
selectRows($yourtable_name);
if($records){
$record_data[‘records’] = $db->selectRows($yourtable_name);
$record_data[‘isactive’] = ‘OK’;
}else{
$record_data[‘records’] = array();
$record_data[‘isactive’] = ‘ERR’;
}
echo json_encode($record_data);
break;
case “add”:
if(!empty($_POST[‘record_data’])){
$itemrecord_data = array(
‘name’ => $_POST[‘record_data’][‘name’],
’email’ => $_POST[‘record_data’][’email’],
‘contact’ => $_POST[‘record_data’][‘contact’]
);
$insert = $db->insert($yourtable_name,$itemrecord_data);
if($insert){
$record_data[‘record_data’] = $insert;
$record_data[‘isactive’] = ‘OK’;
$record_data[‘message’] = ‘item record_data has been added successfully.’;
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
echo json_encode($record_data);
break;
case “edit”:
if(!empty($_POST[‘record_data’])){
$itemrecord_data = array(
‘name’ => $_POST[‘record_data’][‘name’],
’email’ => $_POST[‘record_data’][’email’],
‘contact’ => $_POST[‘record_data’][‘contact’]
);
$condition = array(‘product_id’ => $_POST[‘record_data’][‘product_id’]);
$update = $db->update($yourtable_name,$itemrecord_data,$condition);
if($update){
$record_data[‘isactive’] = ‘OK’;
$record_data[‘message’] = ‘item record_data has been updated successfully.’;
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
echo json_encode($record_data);
break;
case “delete”:
if(!empty($_POST[‘product_id’])){
$condition = array(‘product_id’ => $_POST[‘product_id’]);
$delete = $db->delete($yourtable_name,$condition);
if($delete){
$record_data[‘isactive’] = ‘OK’;
$record_data[‘message’] = ‘item record_data has been deleted successfully.’;
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
}else{
$record_data[‘isactive’] = ‘ERR’;
$record_data[‘message’] = ‘Some error generate or stuck occurred, please try again.’;
}
echo json_encode($record_data);
break;
default:
echo ‘{“isactive”:”INVALproduct_id”}’;
}
}
[/php]
Bootstrap & jQuery Libraries:
[php]
[/php]
AngularJS JavaScript Code:
[php]
// define application
angular.module(“liveApp”, [])
.controller(“itemController”, function($scope,$http){
$scope.products = [];
$scope.tempitemrecord_data = {};
// function to get records from the record_database
$scope.getRecords = function(){
$http.get(‘mainpage.php’, {
params:{
‘type’:’view’
}
}).success(function(result){
if(result.isactive == ‘OK’){
$scope.products = result.records;
}
});
};
// function to insert or update item record_data to the record_database
$scope.saveitem = function(type){
var record_data = $.param({
‘record_data’:$scope.tempitemrecord_data,
‘type’:type
});
var config = {
headers : {
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=utf-8;’
}
};
$http.post(“mainpage.php”, record_data, config).success(function(result){
if(result.isactive == ‘OK’){
if(type == ‘edit’){
$scope.products[$scope.index].product_id = $scope.tempitemrecord_data.product_id;
$scope.products[$scope.index].name = $scope.tempitemrecord_data.name;
$scope.products[$scope.index].email = $scope.tempitemrecord_data.email;
$scope.products[$scope.index].contact = $scope.tempitemrecord_data.contact;
$scope.products[$scope.index].created = $scope.tempitemrecord_data.created;
}else{
$scope.products.push({
product_id:result.record_data.product_id,
name:result.record_data.name,
email:result.record_data.email,
contact:result.record_data.contact,
created:result.record_data.created
});
}
$scope.itemForm.$setPristine();
$scope.tempitemrecord_data = {};
$(‘.myliveform’).slproduct_ideUp();
$scope.messageSuccess(result.message);
}else{
$scope.messageError(result.message);
}
});
};
// function to add item record_data
$scope.additem = function(){
$scope.saveitem(‘add’);
};
// function to edit item record_data
$scope.edititem = function(item){
$scope.tempitemrecord_data = {
product_id:item.product_id,
name:item.name,
email:item.email,
contact:item.contact,
created:item.created
};
$scope.index = $scope.products.indexOf(item);
$(‘.myliveform’).slproduct_ideDown();
};
// function to update item record_data
$scope.updateitem = function(){
$scope.saveitem(‘edit’);
};
// function to delete item record_data from the record_database
$scope.removeItem = function(item){
var conf = confirm(‘Are you sure to delete the item?’);
if(conf === true){
var record_data = $.param({
‘product_id’: item.product_id,
‘type’:’delete’
});
var config = {
headers : {
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=utf-8;’
}
};
$http.post(“mainpage.php”,record_data,config).success(function(result){
if(result.isactive == ‘OK’){
var ltind = $scope.products.indexOf(item);
$scope.products.splice(ltind,1);
$scope.messageSuccess(result.message);
}else{
$scope.messageError(result.message);
}
});
}
};
// function to display success message
$scope.messageSuccess = function(message){
$(‘.alert-success > p’).html(message);
$(‘.alert-success’).show();
$(‘.alert-success’).delay(5000).slproduct_ideUp(function(){
$(‘.alert-success > p’).html(”);
});
};
// function to display error message
$scope.messageError = function(message){
$(‘.alert-danger > p’).html(message);
$(‘.alert-danger’).show();
$(‘.alert-danger’).delay(5000).slproduct_ideUp(function(){
$(‘.alert-danger > p’).html(”);
});
};
});
[/php]
index.html (View File)
[php]
[/php]
CSS Code:
[php]
.none{display: none;}
table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;wproduct_idth: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;cursor: pointer;}
.glyphicon-trash{margin-left: 10px;}
.alert{
wproduct_idth: 50%;
border-radius: 0;
margin-top: 10px;
margin-left: 10px;
}
[/php]
Example
I hope you have Got AngularJS CRUD Example with Material Design – Step by Step And how it works.I would Like to have FeadBack From My Blog(infinityknow.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(infinityknow.com) Are Most Always Welcome.