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. http://exmaple.com/api/api.php
Note: This is just a demo code example to understand the basics. Not to use in Production mode.
<?php
// 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' => 'jon@doe.com'];
// 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: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule
],
Import HttpClient
in src/app/home/home.page.ts
and inject it in the constuctor
method.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private http: HttpClient) {}
apiUrl: string = 'http://exmaple.com/api/api.php';
fetchData() {
this.http.get(this.apiUrl).subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
);
}
}
Add the button to src/app/home/home.page.html
.
<ion-button (click)="fetchData()">Fetch Data</ion-button>
That’s all from me. If you have something to share please comment below. Happy Coding!