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 and PUT 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 vehicles insurance policies. For the sake of simplicity, you are only going to add the following attributes to the policies database table:

  • number: stores to the insurance policy number,
  • amount: stores the insurance amount,
  • creationDate: used to hold the date of the creation of the policy,
  • expireDate: used to hold the the insurance policy expiration date

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 fiw 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, the 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 and responds accordingly by either fetching and returning data from the SQL table or insert, update or delete data from the database.

Create a folder for your project:

$ mkdir angular7-php-app
$ cd angular7-php-app
$ mkdir backend

You create the angular7-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 impents a simple CRUD REST API against a MySQL database.

Next, navigate into your backend project and create a api.php file.

$ cd backend
$ touch api.php

Open the backend/api.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 response headers such as CORS and the allowed methods (PU, 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.

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.

Make sure you change them to your actual MySQL credentials. Also make sure you have created a database with a policies table that has number, amount, creationDate and expireDate 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);
$id = ''

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':
    $sql = "update policies (number, amount, creationDate, expireDate) ('$number', '$amount', '$creationDate', '$expireDate')"; break;
  case 'POST':
    $sql = "insert into policies (number, amount, creationDate, expireDate) ('$number', '$amount', '$creationDate', '$expireDate')"; break;
  case 'DELETE':
    $id = $_GET['id'];
    $sql = "delete policies where id=$id"; break;
}

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

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

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 localhost:8080 address.

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.

The recommended way of creating Angular project 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

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.

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

$ cd angular7-php-app
$ ng new frontend

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

$ cd frontend
$ ng start

You can access the frontend application by pointing your browser to the 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