Angular 7|6 with PHP and MySQL Example & Tutorial

In this tutorial, you'll create an example Angular 7 application with PHP and MySQL back-end.

You will be creating a simple RESTful API that supports GET, POST, PUT and DELETE requests and allow you to perform CRUD operations against a MySQL database to create, read, update and delete records from a database.

For the application design, It's a simple interface for working with vehicle insurance policies. For the sake of simplicity, you are only going to add the following attributes to the policies database table:

  • number which stores to the insurance policy number,
  • amount which stores the insurance amount.

This is of course far from being a complete database design for a fully working insurance system. Because at least you need to add other tables like employees, clients, coverage, vehicles and drivers etc. And also the relationships between all these entities.

Prerequisites

In this tutorial we assume you have the following prerequisites:

  • The MySQL database management system installed on your development machine,
  • PHP installed on your system (both these first requirements are required by the back-end project),
  • Node.js 8.9+ and NPM installed in your system. This is only required by your Angular project.

You also need to have a working experience with PHP and the different functions that will be used to create the SQL connection, getting the GET and POST data and returning JSON data in your code.

You need to be familiar with TypeScript, a superset of JavaScript that's used with Angular.

A basic knowledge of Angular is preferable but not required since you'll go from the first step until your create a project that communicates with a PHP server.

Creating the PHP Application

Let's start by creating a simple PHP script that connects to a MySQL database and listens to API requests then responds accordingly by either fetching and returning data from the SQL table or insert, update and delete data from the database.

Create a folder for your project:

$ mkdir angular-php-app
$ cd angular-php-app
$ mkdir backend

You create the angular-php-app that will contain the full front-end and back-end projects. Next, you navigate inside it and create the backend folder that will contain a simple PHP script that implements a simple CRUD REST API against a MySQL database.

Next, navigate into your backend project and create an index.php file.

$ cd backend
$ touch index.php

Open the backend/index.php file and add the following PHP code step by step:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

These lines are used to add response headers such as CORS and the allowed methods (PUT, GET and POST).

Setting CORS to * will allow your PHP server to accept requests from another domain where the Angular 7 server is running from without getting blocked by the browser by reason of the Same Origin Policy. In development, you'll be running the PHP server from localhost:8080 port and Angular from localhost:4200 which are considered as two distinct domains.

Next, add:

$localhost = "127.0.0.1"; 
$username = "root"; 
$password = "root"; 
$dbname = "mydb"; 

These variables hold the credentials that will be used to connect to the MySQL database and the name of the database.

Note: Make sure you change them to your actual MySQL credentials. Also make sure you have created a database with a policies table that has two number and amount columns.

Next, add:

// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);

This code will allow you to retrieve the HTTP method sent from the client and get the request body.

// create connection to mysql
$conn = new mysqli($localhost, $username, $password, $dbname); 
mysqli_set_charset($conn ,'utf8');

if($conn->connect_error) {
    die("Error : " . $conn->connect_error);
} 

This will allow you to create a connection to the MySQL database using the mysqli extension.

Now, you need to build the appropriate SQL query depending on the HTTP method:

switch ($method) {
  case 'GET':
    $id = $_GET['id'];
    $sql = "select * from policies".($id?" where id=$id":''); break;
  case 'PUT':
    $id = $input["id"];
    $number = $input["number"];
    $amount = $input["amount"];
    $sql = "update policies set number = '$number', amount = $amount where id=$id"; 
    break;
  case 'POST':
    $number = $input["number"];
    $amount = $input["amount"];
    $sql = "insert into policies (number, amount) ('$number', '$amount')"; 
    break;
  case 'DELETE':
    $id = $_GET['id'];
    $sql = "delete from policies where id=$id"; 
    break;
}

// run SQL statement
$result = mysqli_query($conn,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($conn));
}

After building the SQL query, you simply use the mysqli_query function to execute the query.

Next, add this code to fetch results and insert id or affected row count depending on the request method:

// print results, insert id or affected row count
if ($method == 'GET') {
  if (!$id) echo '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$id) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($conn);
} else {
  echo mysqli_affected_rows($conn);
}

Finally add the following code to close the connection with the database:

//Close mysqli database connection
$conn->close();
?>

That's all what you need to add for this simple CRUD REST API script with PHP.

Serving the PHP REST API Project

You can next serve your PHP application using the built-in development server using the following command:

$ php -S 127.0.0.1:8080 -t ./angular7-php-app/backend

This will run a development server from the 127.0.0.1:8080 address.

Creating the MySQL Database

In your terminal, run the following command to start the mysql client:

$ mysql -u root -p

The client will prompt for the password that you configured when installing MySQL in your system.

Next, run this SQL query to create a mydb database:

mysql> create database mydb;

Creating the policies SQL Table

Next create the policies SQL table with two number and amount columns:

mysql> create table policies( id int not null auto_increment, number varchar(20), amount float, primary key(id)); 

Now, you are ready to send GET, POST, PUT and DELETE requests to your PHP server running from the 127.0.0.1:8080 address.

For sending test requests, you can use REST clients such as Postman or cURL before creating the Angular UI.

Leave your server running and open a new terminal.

Creating the Angular 7 Project

Now that you've created the RESTful API with a PHP script, you can proceed to create your Angular 7 project.

Installing Angular CLI 7

The recommended way of creating Angular projects is through using Angular CLI, the official tool created by the Angular team. The latest and best version yet is Angular CLI 7 so head back to another terminal window and run the following command to install the CLI:

$ npm install -g @angular/cli

Note: This will install Angular CLI globally so make sure you have configured npm to install packages globally without adding sudo in Debian systems and macOS or using an administrator command prompt on Windows.

Generating a New project

That's it! You can now use the CLI to create an Angular 7 project using the following command:

$ cd angular-php-app
$ ng new frontend

The CLI will ask you if Would you like to add Angular routing? type y because we'll need routing setup in our application. And Which stylesheet format would you like to use? Select CSS.

Wait for the CLI to generate and install the required dependencies and then you can start your development server using:

$ cd frontend
$ ng serve

You can access the frontend application by pointing your browser to the http://localhost:4200 address.

Conclusion

In this tutorial, you have created a PHP RESTful API that can be used to execute CRUD operations against a MySQL database to create, read, update and delete insurance policies.

You have enabled CORS so you can use two domains localhost:8000 and localhost:4200 for respectively serving PHP and Angular 7 and being able to send requests from Angular to PHP without getting blocked by the Same Origin Policy rule in web browsers.

You have also created an Angular 7 project that will be used to consume the API using HttpClient.


comments powered by Disqus