Home PHP

AngularJS CRUD Tutorial – JavaScript Programming – Step by Step Guide!

php-mysql-angularjs-crud-tutorial

Previously, we have create, read, update and delete database records with our React CRUD Tutorial. Today, we will learn how to do CRUD with AngularJS, PHP and MySQL.

Welcome to the fifth part of the series. I’m happy to see you here, I love to see a person like you who has a great desire for learning!

I highly recommend studying the previous tutorials first before proceeding here. But if you think you can take this one, then go on.

This tutorial will focus on creating, reading, updating, deleting and searching database records. We will do it using a Google’s AngularJS, PHP and MySQL.

As for the user interface, instead of Bootstrap, we will use Materialize CSS – a modern responsive front-end framework based also on Google’s Material Design.

jQuery will also help us a little bit with modals. PDO and OOP will help us with the PHP part.

This will lead to other useful features like pagination, CSV downloads and more.

Contents of this post will include:

1.0 AngularJS CRUD Example PHP – Output
2.0 File Structure

3.0 Database table and connection
3.1 Create the database table
3.2 Dump sample data on the table
3.3 PHP script to connect to database

4.0 Put assets inside certain directories
4.1 Put AngularJS and jQuery libraries in “assets/js/” folder
4.2 Put Materialize CSS framework in “assets/css/” folder

5.0 Create “objects” folder with product.php object file
5.1 Basic code for the “product” class

6.0 Make use of your HTML coding skills
6.1 Create basic HTML code structure for index.html
6.2 Add custom CSS
6.3 Put the most important DIV tag

7.0 Create or insert data using AngularJS and PHP
7.1 HTML code of “create product form”
7.2 HTML button to show the “create product HTML form”
7.3 AngularJS Basic Code
7.4 Create “products” controller
7.5 AngularJS “showCreateForm” function to show “create product form”
7.6 AngularJS “clearForm” function to remove any form values that exists
7.7 AngularJS “createProduct” function
7.8 jQuery script to initialize modal
7.9 PHP code to create a record
7.10 Object code to create a record
7.11 Output should look like this

8.0 Read & search data using AngularJS and PHP
8.1 Display list of data in table
8.2 AngularJS code to read records
8.3 PHP script to read records
8.4 Object code to read records
8.5 Output should look like this

9.0 Update data using AngularJS and PHP
9.1 AngularJS code to read details of record to be edited
9.2 PHP script to read details of a record
9.3 Object code to read single record
9.4 AngularJS code to update a record
9.5 PHP script to update a record
9.6 Object code to update a record
9.7 Output should look like this

10.0 Delete data using AngularJS and PHP
10.1 AngularJS code to delete a record
10.2 PHP script to delete a record
10.3 Object code to delete a record
10.4 Output should look like this

11.0 Pagination of data using AngularJS
11.1 Create “dirPagination.js” file inside “/assets/js/” folder
11.2 Create “dir_pagination.tpl.html” in root folder
11.3 Include angular pagination in index.html
11.4 Apply pagination in table
11.5 Add pagination buttons
11.6 Add pagination directive
11.7 Output should look like this

12.0 What People Say About This Code?
13.0 Download Source Codes
14.0 Related Source Codes
15.0 What’s Next?
16.0 Some Notes

1.0 AngularJS CRUD Example PHP – Output

We usually have three LEVELS of source code output. But WHY? Because I believe in "Learning Progression" to ensure efficient learning. Learn more

1.1 LEVEL 1 Source Code Output


1.2 LEVEL 2 Source Code Output


1.3 LEVEL 3 Source Code Output


The LEVEL 2 and LEVEL 3 source code outputs proves that you can add and customize more features. It’s easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let’s proceed to the step by step tutorial of our LEVEL 1 source code. Enjoy!

For now, let us continue learning the LEVEL 1 source code from section 2.0 onwards.

2.0 File Structure

Knowing the file structure will give us an overview of what PHP files do we need to create and where the assets should be placed.

├─ api/
├─── config/
├────── database.php
├─── objects/
├────── product.php
├─── product/
├────── create.php
├────── delete.php
├────── read.php
├────── read_one.php
├────── update.php
├─ app/
├─── product/
├────── controller.js
├─── shared/
├────── dir_pagination.tpl.html
├─── app.js
├─ assets/
├─── css/
├────── materialize/
├────── custom.css
├─── js/
├────── angular.min.js
├────── custom.js
├────── dirPagination.js
├────── jquery.min.js
├─ dev/
├────── angularjs_crud_level_1.sql
├────── readme.txt
├─ index.html

3.0 Database structure and connection

We have to create a database, then a table with the following table structure, and a PHP file that we will use for database connection.

3.1 Create the database table

Run the following SQL code on your PhpMyAdmin. This is to create our database table. By the way, the database name we used in this tutorial was named “angularjs_crud_level_1”.

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `price` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;

3.2 Dump sample data on the table

Run the following SQL code on your PhpMyAdmin again, this will pre-insert sample data or record on our “products” database table.

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `description`, `price`, `created`, `modified`) VALUES
(1, 'LG Optimus 4X HD P880 Black', 'Display - True HD-IPS LCD - 720 x 1280 pixels, 4.7 inches. Internal Memory - 16 GB storage (12 GB user available), 1 GB RAM. Camera - 8 MP, 3264x2448 pixels, autofocus, LED flash', 309, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(2, 'Motorola Google Nexus 6, Midnight Blue 32GB', 'The stunning 6 inch Quad HD display is great for movies, videos, gaming, e-books, and surfing the Web, and the Nexus 6 provides exceptional battery life.', 400, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(3, 'Samsung Galaxy S4 i9500 16GB', 'Make your life richer, simpler, and more fun. As a real life companion, the new Samsung GALAXY S4 helps bring us closer and captures those fun moments when we are together. Each feature was designed to simplify our daily lives. Furthermore, it cares enough to monitor our health and well being.', 600, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(6, 'Bench Men''s Bench Spokes Slim T-Shirt', 'Make their heads spin by rollin'' through with swag to spare. Cotton-poly heather blend provides for a soft, comfortable wear. Screen printed Bench graphics on front. Slim fitting for modern appeal. Contrast topstitching along shoulders. Ribbed crew neck. Short sleeves', 14, '2014-06-01 01:12:26', '2014-05-31 02:12:21'),
(7, 'HP ZBook 17 Mobile Business Workstation', 'Feel the power! Take performance to a new level with the HP ZBook 17 with Intel''s quad core CPU and 4GB GDDR5 Nvidia Quadro graphics.  Project a professional image at the office, client meetings, and on the road without sacrificing durability in a stylish chassis.', 5149, '2014-06-01 01:13:45', '2014-05-31 02:13:39'),
(8, 'Samsung Galaxy Tab 4', 'Ideal for watching HD movies, playing games, browsing the web, or reading, the Samsung Galaxy Tab 4 features a 10.1-inch, 1280x800 resolution screen, so you experience rich graphics, bright colors, and crisp text.', 210, '2014-06-01 01:14:13', '2014-05-31 02:14:08'),
(9, 'Spalding Men', 'Right from the beginning, it was all about being first, being the best…being what others could only dream of becoming. Founded by Boston Red Stockings pitcher A.G. Spalding in 1876, Spalding has become a leader of innovation and quality in the sporting goods industry.', 49, '2014-06-01 01:18:36', '2014-05-31 02:18:31'),
(10, 'Sony Smart Watch 3', 'Contextually aware and smart, Android Wear gives you useful information at a glance and responds to your voice, feeding you relevant and specific information as you move.', 194, '2014-06-06 17:10:01', '2014-06-05 18:09:51'),
(11, 'Huawei SnapTo', 'Support all GSM 4G LTE Networks ( T-Mobile, AT&T, Straight Talk, NET10, etc.). 75% screen-body ratio and a stylish, leather-texture finish battery cover with a slim design make the phone compac', 179, '2014-06-06 17:11:04', '2014-06-05 18:10:54'),
(12, 'Abercrombie Men''s Lake Arnold Blazer', '100% Gabardine wool imported from Italy. Classic collegiate blazer with heritage A&F crest at left chest pocket. Front pockets with fold-over flaps.', 25, '2014-06-06 17:12:21', '2014-06-05 18:12:11');


As you may have noticed, steps 1 and 2 are both SQL queries. Yes, they can be run at the same time. But I wanted it to be on separate steps to emphasize the SQL queries’ purpose.

3.3 PHP script to connect to database

Create a folder named “config” and inside it, create a database.php file with the following code. It answers how to connect to MySQL database with PDO?

<?php 
class Database{ 

	// specify your own database credentials 
	private $host = "localhost"; 
	private $db_name = "angularjs_crud_level_1"; 
	private $username = "root"; 
	private $password = ""; 
	public $conn; 

	// get the database connection 
	public function getConnection(){ $this->conn = null;
		
		try{
			$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
		}catch(PDOException $exception){
			echo "Connection error: " . $exception->getMessage();
		}
		
		return $this->conn;
	}
}
?>

4.0 Put assets inside certain directories

4.1 Put AngularJS and jQuery libraries in “assets/js/” folder

Download AngularJS and jQuery libraries and put it in “assets/js/” folder. This will enable us to use AngularJS and jQuery libraries even if we are offline.

4.2 Put Materialize CSS framework in “assets/css/” folder

Download Materialize CSS framework and put it in “assets/css/” folder. This will enable us to use Material Design even if we are offline.

5.0 Create “objects” folder with product.php object file

Create “api” folder. Create “objects” folder. Open “objects” folder. Create “product.php” file and put the following code.

<?php 
class Product{ 
	// database connection and table name 
	private $conn; 
	private $table_name = "products"; 

	// object properties 
	public $id; 
	public $name; 
	public $description; 
	public $price; 
	public $created; 

	// constructor with $db as database connection 
	public function __construct($db){ 
		$this->conn = $db;
	}
}
?>

6.0 Make use of your HTML coding skills

6.1 Create basic HTML code structure for index.html

Create the index.html file. This is the only page the user has to interact with. Make it ready for AngularJS, Material Design and jQuery by including the necessary library sources.

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Read Products</title>

	<!-- include material design CSS -->
	<link rel="stylesheet" href="assets/css/materialize/css/materialize.min.css" />

	<!-- include material design icons -->
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

    <!-- include custom CSS -->
	<link rel="stylesheet" href="assets/css/custom.css" />

</head>
<body>

<!-- page content and controls will be here -->

<!-- include angular js -->
<script src="assets/js/angular.min.js"></script>

<!-- include jquery -->
<script type="text/javascript" src="assets/js/jquery.min.js"></script>

<!-- material design js -->
<script src="assets/css/materialize/js/materialize.min.js"></script>

<!-- custom js -->
<script type="text/javascript" src="assets/js/custom.js"></script>

<!-- app -->
<script type="text/javascript" src="app/app.js"></script>

<!-- product -->
<script type="text/javascript" src="app/product/controller.js"></script>

</body>
</html>

6.2 Add custom CSS

Create “assets” folder. Inside it, create “css” folder. Inside it, create “custom.css” file. Open custom.css and put the following code.

<!-- custom CSS -->
<style>
.width-30-pct{
	width:30%;
}

.text-align-center{
	text-align:center;
}

.margin-bottom-1em{
	margin-bottom:1em;
}
</style>

6.3 Put the most important DIV tag

Inside this “div” tag is where every main content of the page will be loaded. Add the following code after the opeing “body” tag.

<div class="container" ng-app="myApp" ng-controller="productsCtrl">
	<div class="row">
		<div class="col s12">
			<h4>Products</h4>
			
			<!-- data from database will be here -->

		</div> <!-- end col s12 -->
	</div> <!-- end row -->
</div> <!-- end container -->

7.0 Create or insert data using AngularJS and PHP

7.1 HTML code of “create product form”

Put the following code under the “h4” tag of the previous section. It is a form shown via modal or pop up. We will also use the same HTML form for updating a record later.

<!-- modal for for creating new product -->
<div id="modal-product-form" class="modal">
	<div class="modal-content">
		<h4 id="modal-product-title">Create New Product</h4>
		<div class="row">
			<div class="input-field col s12">
				<input ng-model="name" type="text" class="validate" id="form-name" placeholder="Type name here..." />
				<label for="name">Name</label>
			</div>
			<div class="input-field col s12">
				<textarea ng-model="description" type="text" class="validate materialize-textarea" placeholder="Type description here..."></textarea>
				<label for="description">Description</label>
			</div>
			<div class="input-field col s12">
				<input ng-model="price" type="text" class="validate" id="form-price" placeholder="Type price here..." />
				<label for="price">Price</label>
			</div>
			<div class="input-field col s12">
				<a id="btn-create-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="createProduct()"><i class="material-icons left">add</i>Create</a>

				<a id="btn-update-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="updateProduct()"><i class="material-icons left">edit</i>Save Changes</a>

				<a class="modal-action modal-close waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">close</i>Close</a>
			</div>
		</div>
	</div>
</div>

7.2 HTML button to show the “create product HTML form”

Put the following code under the previous section’s code, it will make a floating red button located at the lower right corner of the page.

<!-- floating button for creating product -->
<div class="fixed-action-btn" style="bottom:45px; right:24px;">
	<a class="waves-effect waves-light btn modal-trigger btn-floating btn-large red" href="#modal-product-form" ng-click="showCreateForm()"><i class="large material-icons">add</i></a>
</div>

7.3 AngularJS Basic Code

Create “app” folder. Inside that folder, create “app.js” file and put the following code inside it.

var app = angular.module('myApp', []);

7.4 Create “products” controller

Open the “app” folder. Create a “product” folder inside it. Create “controller.js” file and put the following code.

app.controller('productsCtrl', function($scope, $http) {

});

7.5 AngularJS “showCreateForm” function to show “create product form”

Put the following code inside the curly braces of the previous section.

$scope.showCreateForm = function(){

	// clear form
	$scope.clearForm();

	// change modal title
	$('#modal-product-title').text("Create New Product");

	// hide update product button
	$('#btn-update-product').hide();

	// show create product button
	$('#btn-create-product').show();

}

7.6 AngularJS “clearForm” function to remove any form values that exists

Put the following code under the code of the previous section.

// clear variable / form values
$scope.clearForm = function(){
	$scope.id = "";
	$scope.name = "";
	$scope.description = "";
	$scope.price = "";
}

7.7 AngularJS “createProduct” function

The following code is triggered when the “Create Product” button on the modal or pop up form was clicked. Put the following code under the previous section’s code.

// create new product
$scope.createProduct = function(){

	$http({
		method: 'POST',
		data: {
			'name' : $scope.name,
			'description' : $scope.description,
			'price' : $scope.price
		},
		url: 'api/product/create.php'
	}).then(function successCallback(response) {

		// tell the user new product was created
		Materialize.toast(response.data, 4000);

		// close modal
		$('#modal-product-form').modal('close');

		// clear modal content
		$scope.clearForm();

		// refresh the list
		$scope.getAll();
	});
}

7.8 jQuery script to initialize modal

This small jQuery script will initialize our modal or pop up. This modal is used for “create product” and “update product” pop up forms.

Open “assets” folder. Open “js” folder. Create “custom.js” file and put the following code.

$(document).ready(function(){
	// initialize modal
	$('.modal').modal();
});

7.9 PHP code to create a record

The “create.php” file will receive all the data inputted by the user.

Open “api” folder. Create “product” folder. Open “product” folder and create “create.php” file and put the following code inside it.

<?php
// include database and object file
include_once '../config/database.php';
include_once '../objects/product.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// instantiate product object
$product = new Product($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;
$product->created = date('Y-m-d H:i:s');

// create the product
if($product->create()){
	echo "Product was created.";
}

// if unable to create the product, tell the user
else{
	echo "Unable to create product.";
}
?>

7.10 Object code to create a record

Open “api” folder. Open “objects” folder. Open “product.php” file. Put the following code inside the curly braces of our “Product” class.

// create product
function create(){
	
	// query to insert record
	$query = "INSERT INTO 
				" . $this->table_name . " 
			SET 
				name=:name, price=:price, description=:description, created=:created";
	
	// prepare query
	$stmt = $this->conn->prepare($query);

	// posted values
	$this->name=htmlspecialchars(strip_tags($this->name));
	$this->price=htmlspecialchars(strip_tags($this->price));
	$this->description=htmlspecialchars(strip_tags($this->description));

	// bind values
	$stmt->bindParam(":name", $this->name);
	$stmt->bindParam(":price", $this->price);
	$stmt->bindParam(":description", $this->description);
	$stmt->bindParam(":created", $this->created);
	
	// execute query
	if($stmt->execute()){
		return true;
	}else{
		echo "<pre>";
			print_r($stmt->errorInfo());
		echo "</pre>";

		return false;
	}
}

7.11 Output should look like this

1-angular-js-php-crud-create-product

8.0 Read & search data using AngularJS and PHP

8.1 Display list of data in table

Open index.html and put the following code under the “h4” tag.

<!-- used for searching the current list -->
<input type="text" ng-model="search" class="form-control" placeholder="Search product...">

<!-- table that shows product record list -->
<table class="hoverable bordered">
	<thead>
		<tr>
			<th class="text-align-center">ID</th>
			<th class="width-30-pct">Name</th>
			<th class="width-30-pct">Description</th>
			<th class="text-align-center">Price</th>
			<th class="text-align-center">Action</th>
		</tr>
	</thead>
	<tbody ng-init="getAll()">
		<tr ng-repeat="d in names | filter:search">
			<td class="text-align-center">{{ d.id }}</td>
			<td>{{ d.name }}</td>
			<td>{{ d.description }}</td>
			<td class="text-align-center">{{ d.price }}</td>
			<td>
				<a ng-click="readOne(d.id)" class="waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">edit</i>Edit</a>
				<a ng-click="deleteProduct(d.id)" class="waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">delete</i>Delete</a>
			</td>
		</tr>
	</tbody>
</table>

8.2 AngularJS code to read records

Open “app” folder. Open “product” folder. Open “controller.js” file and put the following code before “$scope.showCreateForm = function(){“.

// read products
$scope.getAll = function(){
	$http({
		method: 'GET',
		url: 'api/product/read.php'
	}).then(function successCallback(response) {
		$scope.names = response.data.records;
	});
}

8.3 PHP script to read records

The following code will it will retrieve records from the database and render the data in JSON format.

Open “api” folder. Open “product” folder. Create “read.php” file and put the following code.

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once '../objects/product.php';

// instantiate database and product object
$database = new Database();
$db = $database->getConnection();

// initialize object
$product = new Product($db);

// query products
$stmt = $product->readAll();
$num = $stmt->rowCount();

$data="";

// check if more than 0 record found
if($num>0){

	
	$x=1;

	// retrieve our table contents
	// fetch() is faster than fetchAll()
	// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
		// extract row
		// this will make $row['name'] to
		// just $name only
		extract($row);

		$data .= '{';
			$data .= '"id":"'  . $id . '",';
			$data .= '"name":"'   . $name . '",';
			$data .= '"description":"'   . html_entity_decode($description) . '",';
			$data .= '"price":"' . $price . '"';
		$data .= '}';

		$data .= $x<$num ? ',' : '';

		$x++;
	}
}

// json format output
echo '{"records":[' . $data . ']}';
?>

8.4 Object code to read records

The previous section will not work without the following code.

Open “api” folder. Open “objects” folder. Open “product.php” file and put the following code before the closing curly brace of the Product class.

// read products
function readAll(){

	// select all query
	$query = "SELECT
				id, name, description, price, created
			FROM
				" . $this->table_name . "
			ORDER BY
				id DESC";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// execute query
	$stmt->execute();

	return $stmt;
}

8.5 Output should look like this

Now we can view the product list and try the search feature.

2-angular-js-php-crud-read-products

9.0 Update data using AngularJS and PHP

9.1 AngularJS code to read details of record to be edited

The following code will help put the details of record to be edited to our HTML form.

Open “app” folder. Open “product” folder. Open “controller.js” file and put the following code before “$scope.getAll = function(){” code.

// retrieve record to fill out the form
$scope.readOne = function(id){

	// change modal title
	$('#modal-product-title').text("Edit Product");

	// show udpate product button
	$('#btn-update-product').show();

	// show create product button
	$('#btn-create-product').hide();

	// post id of product to be edited
	$http({
		method: 'POST',
		data: { 'id' : id },
		url: 'api/product/read_one.php'
	}).then(function successCallback(response) {

		// put the values in form
		$scope.id = response.data[0]["id"];
		$scope.name = response.data[0]["name"];
		$scope.description = response.data[0]["description"];
		$scope.price = response.data[0]["price"];

		// show modal
		$('#modal-product-form').modal('open');
	})
	.error(function(data, status, headers, config){
		Materialize.toast('Unable to retrieve record.', 4000);
	});
}

9.2 PHP script to read details of a record

The previous section will not work without this section. Open “api” folder. Open “product” folder. Create “read_one.php” file, open that file and put the following code.

<?php 
// include database and object files 
include_once '../config/database.php'; 
include_once '../objects/product.php'; 

// get database connection 
$database = new Database(); 
$db = $database->getConnection();

// prepare product object
$product = new Product($db);

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));     

// set ID property of product to be edited
$product->id = $data->id;

// read the details of product to be edited
$product->readOne();

// create array
$product_arr[] = array(
	"id" =>  $product->id,
	"name" => $product->name,
	"description" => $product->description,
	"price" => $product->price
);

// make it json format
print_r(json_encode($product_arr));
?>

9.3 Object code to read single record

Put the following code inside our objects/product.php file.
Open “api” folder. Open “objects” folder. Open “product.php” file and put the following code before “function create(){” code.

// used when filling up the update product form
function readOne(){
	
	// query to read single record
	$query = "SELECT 
				name, price, description  
			FROM 
				" . $this->table_name . " 
			WHERE 
				id = ? 
			LIMIT 
				0,1";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	
	// bind id of product to be updated
	$stmt->bindParam(1, $this->id);
	
	// execute query
	$stmt->execute();

	// get retrieved row
	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	
	// set values to object properties
	$this->name = $row['name'];
	$this->price = $row['price'];
	$this->description = $row['description'];
}

9.4 AngularJS code to update a record

The following code will be triggered when the “Save Changes” button in the modal was clicked.

Open “app” folder. Open “product” folder. Open “controller.js” file and put the following code before “$scope.readOne = function(id){” code.

// update product record / save changes
$scope.updateProduct = function(){
	$http({
		method: 'POST',
		data: {
			'id' : $scope.id,
			'name' : $scope.name,
			'description' : $scope.description,
			'price' : $scope.price
		},
		url: 'api/product/update.php'
	}).then(function successCallback(response) {

		// tell the user product record was updated
		Materialize.toast(response.data, 4000);

		// close modal
		$('#modal-product-form').modal('close');

		// clear modal content
		$scope.clearForm();

		// refresh the product list
		$scope.getAll();
	});
}

9.5 PHP script to update a record

The previous section will not work without this section. Open “api” folder. Open “product” folder. Create “update.php” file, open that file and put the following code.

<?php 
// include database and object files 
include_once '../config/database.php'; 
include_once '../objects/product.php'; 

// get database connection 
$database = new Database(); 
$db = $database->getConnection();

// prepare product object
$product = new Product($db);

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));     

// set ID property of product to be edited
$product->id = $data->id;

// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;

// update the product
if($product->update()){
	echo "Product was updated.";
}

// if unable to update the product, tell the user
else{
	echo "Unable to update product.";
}
?>

9.6 Object code to update a record

The previous section will not work without his section. Open “api” folder. Open “objects” folder. Open “product.php” file and put the following code before “function readOne(){” code.

// update the product
function update(){

	// update query
	$query = "UPDATE
				" . $this->table_name . "
			SET
				name = :name,
				price = :price,
				description = :description
			WHERE
				id = :id";

	// prepare query statement
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->name=htmlspecialchars(strip_tags($this->name));
	$this->price=htmlspecialchars(strip_tags($this->price));
	$this->description=htmlspecialchars(strip_tags($this->description));
	$this->id=htmlspecialchars(strip_tags($this->id));

	// bind new values
	$stmt->bindParam(':name', $this->name);
	$stmt->bindParam(':price', $this->price);
	$stmt->bindParam(':description', $this->description);
	$stmt->bindParam(':id', $this->id);

	// execute the query
	if($stmt->execute()){
		return true;
	}else{
		return false;
	}
}

9.7 Output should look like this

When you clicked an “Edit” button in the product list, you should see the modal with form data of record to be edited.
3-angular-js-php-crud-update-product

10.0 Delete data using AngularJS and PHP

10.1 AngularJS code to delete a record

Open “app” folder. Open “product” folder. Open “controller.js” file and put the following code before “” code.

// delete product
$scope.deleteProduct = function(id){

	// ask the user if he is sure to delete the record
	if(confirm("Are you sure?")){

		$http({
			method: 'POST',
			data: { 'id' : id },
			url: 'api/product/delete.php'
		}).then(function successCallback(response) {

			// tell the user product was deleted
			Materialize.toast(response.data, 4000);

			// refresh the list
			$scope.getAll();
		});
	}
}

10.2 PHP script to delete a record

The previous section will not work without this section. Open “api” folder. Open “product” folder. Create “delete.php” file, open that file and put the following code inside it.

<?php 
// include database and object file 
include_once '../config/database.php'; 
include_once '../objects/product.php'; 

// get database connection 
$database = new Database(); 
$db = $database->getConnection();

// prepare product object
$product = new Product($db);

// get product id
$data = json_decode(file_get_contents("php://input"));     

// set product id to be deleted
$product->id = $data->id;

// delete the product
if($product->delete()){
	echo "Product was deleted.";
}

// if unable to delete the product
else{
	echo "Unable to delete object.";
}
?>

10.3 Object code to delete a record

Open “api” folder. Open “objects” folder. Open “product.php” file and put the following code before “function update(){” code.

// delete the product
function delete(){

	// delete query
	$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

	// prepare query
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->id=htmlspecialchars(strip_tags($this->id));

	// bind id of record to delete
	$stmt->bindParam(1, $this->id);

	// execute query
	if($stmt->execute()){
		return true;
	}

	return false;
}

10.4 Output should look like this

When a delete button was clicked, it will show a confirmation pop up. When the user clicked “Ok”, a toast message will appear confirming the deletion of a record.

4-angular-js-php-crud-delete-product

11.0 Pagination of data using AngularJS

Please note that this is a bonus section. Pagination feature is part of the LEVEL 2 source code download.

11.1 Create “dirPagination.js” file inside “/assets/js/” folder

After creating “dirPagination.js” file inside “/assets/js/” folder, put this code inside. I won’t paste the code here because it’s kinda long. Props to Michael Bromley.

11.2 Create “dir_pagination.tpl.html” in root folder

Once created, put the following code inside the dir_pagination.tpl.html file.

<ul class="pagination" ng-if="1 < pages.length">
	<li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == 1 }">
		<a href="" ng-click="setCurrent(1)">First</a>
	</li>
	<li ng-if="directionLinks" ng-class="{ disabled : pagination.current == 1 }" class="ng-scope">
		<a href="" ng-click="setCurrent(pagination.current - 1)" class="ng-binding">
			<i class="material-icons">chevron_left</i>
		</a>
	</li>
	<li ng-repeat="pageNumber in pages track by $index" ng-class="{ active : pagination.current == pageNumber, disabled : pageNumber == '...' }">
		<a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a>
	</li>

	<li ng-if="directionLinks" ng-class="{ disabled : pagination.current == pagination.last }" class="ng-scope">
		<a href="" ng-click="setCurrent(pagination.current + 1)" class="ng-binding">
			<i class="material-icons">chevron_right</i>
		</a>
	</li>
	<li ng-if="boundaryLinks"  ng-class="{ disabled : pagination.current == pagination.last }">
		<a href="" ng-click="setCurrent(pagination.last)">Last</a>
	</li>
</ul>

11.3 Include angular pagination in index.html

On our index.html, find:

<script src="assets/js/angular.min.js"></script>

And put the following code after it.

<!-- include angular pagination -->
<script src="assets/js/dirPagination.js"></script>

11.4 Apply pagination in table

On our table in index.html, find:

<tr ng-repeat="d in names | filter:search">

and replace it with:

<tr dir-paginate="d in names | filter:search | orderBy:sortKey:reverse | itemsPerPage:5" pagination-id="prodx">

11.5 Add pagination buttons

On index.html, find the ending table tag. Add the following code after it.

<!-- angular pagination -->
<dir-pagination-controls pagination-id="prodx" boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="dir_pagination.tpl.html"></dir-pagination-controls>

11.6 Add pagination directive

Open “app” folder. Open “app.js” file. Replace the following code:

var app = angular.module('myApp', []);

with:

var app = angular.module('myApp', ['angularUtils.directives.dirPagination']);

11.7 Output should look like this

php angularjs pagination

12.0 What People Say About This Code?

We tried to share this post online and the following are what people think.

testimonial-1-angularjs-crud-example-php

testimonial-2-angularjs-crud-example-php

13.0 Source Code Download

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

12.1 Download the LEVEL 1 Source Code

FEATURESLEVEL 1
PDO extension usedYES
Google’s Angular JS enabledYES
Google’s Material Design user interfaceYES
Create productYES
Read productYES
Update productYES
Delete productYES
Price display with dollar signYES
SQL file in “dev” folderYES
LEVEL 1: BUY AND DOWNLOAD NOW USING

12.2 Download the LEVEL 2 Source Code

FEATURESLEVEL 2
All features of LEVEL 1 aboveYES
Front-end validation for create productYES
Front-end validation for update productYES
Category selection for create and update product.YES
Buttons with GlyphiconsYES
Products paginationYES
Search products by name, description, price or category nameYES
Search product list while typing keywordsYES
Pagination in searchYES
Export / download product records to CSVYES
Price display with dollar sign and commaYES
Multiple product deleteYES
LEVEL 2: BUY AND DOWNLOAD NOW USING

12.3 Download the LEVEL 3 Source Code

FEATURESLEVEL 3
All features of LEVEL 1 and 2 aboveYES
Simple product and category navigationYES
Select category in navigationYES
View products by categoryYES
Create categoryYES
Read categoryYES
Update categoryYES
Delete categoryYES
Pagination for categoryYES
Search categoryYES
Pagination for category searchYES
Real-time update of category in drop-downsYES
Sorting by category fieldsYES
Pagination for sorting by fieldsYES
Google’s material design enabledYES
LEVEL 3: BUY AND DOWNLOAD NOW USING

Do you need more reasons to get it?

MORE REASONS TO DOWNLOAD THE CODEALL
Use new skills for your multiple projectsYES
Save huge amount of time learning PHP, AngularJS and Material DesignYES
Code examples are direct to the pointYES
Well explained and commented source codeYES
Fast and friendly email supportYES
Free source code updatesYES

12.4 Download ALL LEVELS in Separate Packages

DOWNLOAD ALL 3 PACKAGES ABOVEALL
Level 1 source code packageYES
Level 2 source code packageYES
Level 3 source code packageYES
ALL LEVEL: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

If you have any more questions, please feel free to contact me now. You can do it by sending a message on our official Facebook page, or via my email mike@codeofaninja.com

Thanks for supporting our website and projects here at codeofaninja.com!

14.0 Related Source Codes

The following related source code tutorials can be very useful to further improve your skills.

PHP CRUD Tutorials
1.0 PHP & MySQL CRUD Tutorial for Beginners
2.0 PHP, MySQL & OOP CRUD Tutorial
3.0 PHP, MySQL & AJAX CRUD Tutorial
4.0 PHP, MySQL & AngularJS CRUD Tutorial
5.0 PHP, MySQL & React CRUD Tutorial
PHP Shopping Cart Tutorials
1.0 Shopping Cart Tutorial using SESSIONS
2.0 Shopping Cart Tutorial using COOKIES
3.0 Shopping Cart Tutorial using MySQL
PHP Web Application Source Codes
PHP Shopping Cart System
PayPal Integration In PHP
PHP Login System

15.0 What’s Next?

We just learned how to use AngularJS and Material Design. You have two choices where to go next.

A. Learn a new AngularJS script. This script is an addition to our tutorial above. Studying this script will help you learn more coding techniques with PHP and AngularJS. Some include learning a better file structure, working with 4 objects, dynamic drop-down data (retrieved from database), routing and more.

We call this script “simple tournament script” because it features four objects related to a tournament: matches, countries, tournaments and teams.

Click the following link to learn more: Simple PHP Tournament Script – PHP & AngularJS

B. Learn our Angular 2 CRUD Tutorial. – this time, we will learn how to create, read, update and delete database records with Node.js and Angular 2. Click the following link: Node.js & Angular CRUD Tutorial – Step By Step Guide!

16.0 Some Notes

Important note:

  • If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page! Please be more detailed about your issue. Best if you can provide your test URL. Thanks!
  • Source code levels 1-3 above works well with smaller AngularJS apps and database size. Once you reached a certain database size, your data needs to be loaded asynchronously. For example, the server will only send one page of data at a time. We will add these asynchronous data features in LEVEL 3 source code in the future.

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Thanks for reading our step by step tutorial about AngularJS CRUD Example with PHP, MySQL and Material Design!