This tutorial will help you to learn angular CRUD operation using PHP and MySQL. This tutorial is divided into two parts. One for PHP & MySQL code and another for angular code.
PHP and MYSQL Part:
Steps:
1. Create a database named angdb.
2. Create a table named ‘products‘ with the following fields.
CREATE TABLE `products`
(`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`price` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`));
3. Add some records in the table
insert into products (id,name,price)
values(null, 'HDD',6000),
(null, 'Monitor',8000),
(null, 'Printer',10000),
(null,'Scanner',5000);
4. Create a folder named ‘ang-php-mysql‘ and create a folder named ‘api‘ under that folder.
5. Create the following PHP files under api folder.
index.php
create_product.php
update_product.php
delete_product.php
database.php
6. Add the following content in database.php for database connection.
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Content-Type: application/json; charset=UTF-8");
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('NAME', 'angdb');
$db = new mysqli(HOST ,USER ,PASS ,NAME);
if ($db->connect_errno) {
die("Database connection error:" . $db->connect_errno);
}
?>
7. Add the following content in index.php for displaying all products.
<?php
include 'database.php';
$products = [];
$sql = "SELECT * FROM products";
if($result = $db->query($sql))
{
$i = 0;
while($row = $result->fetch_assoc())
{
$products[$i]['id'] = $row['id'];
$products[$i]['name'] = $row['name'];
$products[$i]['price'] = $row['price'];
$i++;
}
echo json_encode($products);
}
else
{
http_response_code(404);
}
8. Add the following content in create_product.php for inserting new product.
<?php
include 'database.php';
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata,true);
// Validate.
if(trim($request['name']) === '' || (float)$request['price'] < 0)
{
return http_response_code(400);
}
$name = mysqli_real_escape_string($db, trim($request['name']));
$price = mysqli_real_escape_string($db, (int)$request['price']);
$sql = "INSERT INTO products (id,name,price) VALUES (null,'$name',$price)";
if($db->query($sql))
{
http_response_code(201);
$product = [
'id' => mysqli_insert_id($db),'name' => $name,
'price' => $price];
echo json_encode($product);
}
else
{
http_response_code(422);
}
}
9. Add the following content in update_product.php to update existing product.
<?php
require 'database.php';
$postdata = file_get_contents('php://input');
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata,true);
if (trim($request['name']) == '' || (float)$request['price'] < 0) {
return http_response_code(400);
}
$id = mysqli_real_escape_string($db, (int)$request['id']);
$name = mysqli_real_escape_string($db, trim($request['name']));
$price = mysqli_real_escape_string($db, (float)$request['price']);
$sql = "UPDATE products SET name='$name',price=$price WHERE id = $id";
if($db->query($sql))
{
http_response_code(204);
}
else
{
return http_response_code(422);
}
}
10. Add the following content in delete_product.php to delete existing product.
<?php
require 'database.php';
$id = ($_GET['id'] !== null && (int)$_GET['id'] > 0)? mysqli_real_escape_string($db, (int)$_GET['id']) : false;
if(!$id)
{
return http_response_code(400);
}
$sql = "DELETE FROM products WHERE id =$id";
if($db->query($sql))
{
http_response_code(204);
}
else
{
return http_response_code(422);
}
Angular Part:
Steps:
1. Go to the project folder and run the following command to create a new angular project named ‘ang-crud‘. You must press ‘y’ when the command will ask for routing module.
ng new ang-crud
If you didn’t install angular 8 before then you have to install it first before running the above command. You can follow the tutorial given in the following link to install angular 8 with bootstrap.
https://fahmidasclassroom.com/angular-8-installation/
2. Install and setup bootstrap for your angular project.
3. Add the following lines in app.module.ts to add FormsModule and HttpClientModule.
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
4. Add the following modules in the import section.
HttpClientModule
FormsModule
Remove all parts of AppComponent and add ProductsComponent in bootstrap section in app.module.ts file.
5. Run the following command from the project folder to create service for communicating with PHP codes.
ng generate service api
6. Create a model name product.ts under src/app folder and add the following code.
export class Product {
id: number;
name: string;
price: number;
}
7. Open the src/app/api.service.ts file and import the Product model and the RxJS Observable interface.
import { Product } from './product';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
8. Modify the ApiService class with the following code.
export class ApiService {
PHP_API_SERVER = "http://localhost/ang-php-mysql/api";
constructor(private httpClient: HttpClient) {}
readProducts(): Observable<Product[]>{
return this.httpClient.get<Product[]>(`${this.PHP_API_SERVER}/index.php`);
}
createProduct(product: Product): Observable<Product>{
return this.httpClient.post<Product>(`${this.PHP_API_SERVER}/create_product.php`, product);
}
updateProduct(product: Product){
return this.httpClient.put<Product>(`${this.PHP_API_SERVER}/update_product.php`, product);
}
deleteProduct(id: number){
return this.httpClient.delete<Product>(`${this.PHP_API_SERVER}/delete_product.php/?id=${id}`);
}
}
9. Run the following command to create component for products.
ng generate component products
10. Open the src/app/app-routing.module.ts file and add a /dashboard route for products.
import { ProductsComponent } from './products/products.component';
const routes: Routes = [
{ path: 'dashboard', component: ProductsComponent }
];
11. Open the src/app/app.component.html file and add the following line.
<router-outlet></router-outlet>
12. open the src/app/products/products.component.ts file and import ApiService and Product.
import { ApiService } from '../api.service';
import { Product } from '../product';
13. Change the selector.
selector: 'router-outlet'
14. Modify ProductsComponent class with the following code.
export class ProductsComponent implements OnInit {
products: Product[];
selectedProduct: Product = { id : null , name: null, price: null}
constructor(private apiService: ApiService) {
this.apiService.readProducts().subscribe((products: Product[])=>{
this.products = products;
console.log(this.products);
}) }
ngOnInit()
{
}
createOrUpdateProduct(form){
form.value.id = this.selectedProduct.id;
form.value.name = this.selectedProduct.name;
form.value.price = this.selectedProduct.price;
if(this.selectedProduct && this.selectedProduct.id){
this.apiService.updateProduct(form.value).subscribe((product: Product)=>{
console.log("Product updated" , product);
this.apiService.readProducts().subscribe((products: Product[])=>{
this.products = products;
})
});
}
else{
this.apiService.createProduct(form.value).subscribe((product: Product)=>{
console.log("Product created, ", product);
this.apiService.readProducts().subscribe((products: Product[])=>{
this.products = products;
})
});
}
}
selectProduct(product: Product){
this.selectedProduct = product;
}
deleteProduct(id){
this.apiService.deleteProduct(id).subscribe((product: Product)=>{
console.log("Product deleted, ", product);
this.apiService.readProducts().subscribe((products: Product[])=>{
this.products = products;
})
});
}
}
15. Open the src/app/products/products.component.html and add the following HTML code.
<h1>Product Management System</h1>
<form #f = "ngForm">
<label>Name</label>
<input type="text" name="name" [(ngModel)] = "selectedProduct.name">
<br>
<label>Amount</label>
<input type="text" name="price" [(ngModel)] = "selectedProduct.price">
<br>
<input type="button" (click)="createOrUpdateProduct(f)" value="Create or Update Product">
</form>
<br/>
<div>
<table class="table table-striped table-bordered">
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Product Price</th>
<th>Operations</th>
</tr>
<tr *ngFor="let product of products">
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
<td>
<button (click)="selectProduct(product)">Edit</button>
<button id="del" (click)="deleteProduct(product.id)">Delete</button>
</td>
</tr>
</table>
16. Open the src/app/products/products.component.css file and add the following CSS code.
input {
width: 100%;
padding: 2px 5px;
margin: 2px 0;
border-radius: 4px;
box-sizing: border-box;
}
button, input[type=button]{
background-color: #4CAF50;
border: none;
color: white;
padding: 4px 7px;
text-decoration: none;
margin: 2px 1px;
cursor: pointer;
}
#del
{
background-color: red;
border: none;
}
th, td {
padding: 1px;
text-align: left;
border-bottom: 1px solid #ddd;
}
tr:hover {background-color: #f5f5f5;}
17. Open the index.html under src/ folder and replace the body tag with the following content.
<body>
<router-outlet></router-outlet>
</body>
18. Run the following command to install cors package.
***Note: If you get any cross-browser origin error then do the following steps.
Run the following command
npm i cors
Create a file named proxy.conf.json with the following code.
{
"/api/*": {
"target": "http://localhost:4200",
"secure": false,
"logLevel": "debug"
}
}
Add the following line in angular.json file under serve section.
"proxyConfig": "src/proxy.conf.json"
Good Luck.
Session handling using Angular 8 is given in the following tutorial.