0% found this document useful (0 votes)
293 views

Angular CRUD Using PHP and MySQL

Uploaded by

jagruti patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
293 views

Angular CRUD Using PHP and MySQL

Uploaded by

jagruti patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

FahmidasClassroom

Learn by easy steps


(https://fahmidasclassroom.com/)

PRICE DROP

Flat 60% Off | Shop Now


Bath & Body Works

Home (https://fahmidasclassroom.com) / Web Programming (https://fahmidasclassroom.com/category/web-programming/) / Framework (https://fahmidasclassroom.com/category/web-programming/framework/)


Angular CRUD using PHP and MySQL

Angular CRUD using PHP and MySQL Search …

Fahmida Yesmin (https://fahmidasclassroom.com/author/webtutor/)

 December 8, 2019 (https://fahmidasclassroom.com/2019/12/08/)

Email Subscribe

Categories

(https://fahmidasclassroom.com
programming/fram

(https://fahmidasclassroom.com
programming/frame

(https://fahmidasclassroom.com
de


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.
(https://fahmidasclassroom.com
pro
PHP and MYSQL Part:
Steps:
1. Create a database named angdb. (https://fahmidasclassroom.com
programming/framewo
2. Create a table named ‘products‘ with the following fields.

CREATE TABLE `products`

(`id` int(11) NOT NULL AUTO_INCREMENT,

(https://fahmidasclassroom.com
`name` varchar(100) NOT NULL,

`price` decimal(10,2) NOT NULL,

PRIMARY KEY (`id`));

3. Add some records in the table (https://fahmidasclassroom.com

insert into products (id,name,price)

values(null, 'HDD',6000),

(null, 'Monitor',8000),

(https://fahmidasclassroom.com
(null, 'Printer',10000),

(null,'Scanner',5000);

4. Create a folder named ‘ang-php-mysql‘ and create a folder named ‘api‘ under that folder.
(https://fahmidasclassroom.com
programm

(https://fahmidasclassroom.com

(https://fahmidasclassroom.com

Flat 60% Off | Shop Now


Bath & Body Works

5. Create the following PHP files under api folder.


(https://fahmidasclassroom.com

Data Management (https://fahmidasclassroom.com


Courses de

Free comparison tool for finding Data


Management courses online.
(https://fahmidasclassroom.com
progr

Coursary Open


(https://fahmidasclassroom.com
index.php
programming/fram
create_product.php

update_product.php

delete_product.php

database.php

(https://fahmidasclassroom.com
6. Add the following content in database.php for database connection. programming

(https://fahmidasclassroom.com


<?php

header("Access-Control-Allow-Origin: *");
(https://fahmidasclassroom.com
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");


(https://fahmidasclassroom.com
define('HOST', 'localhost');

define('USER', 'root');

define('PASS', '');

define('NAME', 'angdb');

(https://fahmidasclassroom.com

$db = new mysqli(HOST ,USER ,PASS ,NAME);

if ($db->connect_errno) {

die("Database connection error:" . $db->connect_errno);

}
(https://fahmidasclassroom.com
?>
pro

Data Management (https://fahmidasclassroom.com

Courses
Free comparison tool for finding Data (https://fahmidasclassroom.com
Management courses online.

Coursary Open (https://fahmidasclassroom.com


progra
7. Add the following content in index.php for displaying all products.

(https://fahmidasclassroom.com
Data Management
Courses
Free comparison tool for finding Data
(https://fahmidasclassroom.com
Management courses online.

W
Coursary Open (https://fahmidasclassroom.com

<?php

include 'database.php';

$products = [];


(https://fahmidasclassroom.com
$sql = "SELECT * FROM products";

if($result = $db->query($sql))

$i = 0;

(https://fahmidasclassroom.com
while($row = $result->fetch_assoc())

programming/
$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);

00:00 00:00
// 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/ (https://fahmidasclassroom.com/angular-8-installation/)


2. Install and setup bootstrap for your angular project.

i
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`, produc


t);

updateProduct(product: Product){

return this.httpClient.put<Product>(`${this.PHP_API_SERVER}/update_product.php`, produc


t);

deleteProduct(id: number){

return this.httpClient.delete<Product>(`${this.PHP_API_SERVER}/delete_product.php/?id=${i
d}`);

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.

Register and Login System using Angular 8, PHP and


MySQL
This is a simple tutorial of Angular 8 to create a Register and Login System with the use
of PHP and MySQL. You have to follow the steps properly to complete the tutorial.
Steps: 1. Create a table named users (id(auto-increment) , name, password, email) in
your angular database. 2. Create a new angular project … Continue reading

FahmidasClassroom
15

© Copyright 2022

You might also like