How to connect Ionic 4 with PHP and MySQL.

A Few days ago I had to write a hybrid app using the Ionic framework. I choosed PHP and MySQL for backend/API part as I mostly work on the LAMP stack.

Now, I am going to share my experience with Ionic 4 with PHP and MySQL. Here, I will try to write very basic about how actually Ionic 4, PHP and MySQL connect and work together.

First, we need to generate a default demo ionic app, creating a MySQL database and connecting it with PHP. Then follow the steps below:

Create the simple API file.
Note: This is just a demo code example to understand the basics. Not to use in Production mode.

// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

require 'con.php'; // database connection file

// operations to get data from database

// example data formate
$data = ['name' => 'John Doe', 'email' => ''];
// make data json type
echo json_encode($data);

In order to make HTTP requests in an Ionic/Angular environment, we need to make use of the HttpClient and HttpClientModule.

Import the HttpClientModule in src/app/app.module.ts

import { HttpClientModule } from '@angular/common/http';

Add the HttpClientModule to the imports array in src/app/app.module.ts

imports: [

Import HttpClient in src/app/home/ and inject it in the constuctor method.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

  selector: 'app-home',
  templateUrl: '',
  styleUrls: [''],
export class HomePage {

  constructor(private http: HttpClient) {}

  apiUrl: string = '';

  fetchData() {
      res => {
      err => {


Add the button to src/app/home/

<ion-button (click)="fetchData()">Fetch Data</ion-button>

That’s all from me. If you have something to share please comment below. Happy Coding!