Ionic PHP MySQL Example

ionic-php-mysql-example

This lesson, we're going to learn how to read/write data from PHP & MySQL.

**Project:** Need to create simple product manager, where user can enter product information such as title, description, price and picture URL & he can also read data from database

Requirement: we need to create JSON based Web service with PHP & MySQL. I already created simple web service using PHP. Note: It's a very simple code which is not included any security.

Create Database & Table

Note: you can use any database name

CREATE TABLE `products` (
`id` int(10) NOT NULL,
`title` varchar(50) NOT NULL,
`desc` varchar(500) NOT NULL,
`price` varchar(10) NOT NULL,
`pic` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
ALTER TABLE `products` ADD PRIMARY KEY ( `id` );
ALTER TABLE `products` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;

Web Service with PHP

Connecting with database db.php

<?php
header("Access-Control-Allow-Origin: *"); 
$con = mysqli_connect("localhost", "root", "root", "phonegap_webservice") or die("could not connect DB"); 
?>

Insert data into database product.php

<?php
include "db.php"; 
$input = file_get_contents('php://input'); 
$data = json_decode($input, true); 
$message = array(); 
if($data['action'] == "insert"){
    $title = $data['title']; 
    $desc = $data['desc']; 
    $price = $data['price']; 
    $pic = $data['pic']; 
    $q = mysqli_query($con, "INSERT INTO `products` ( `title` , `desc` , `price` , `pic` ) VALUES ('$title', '$desc', '$price', '$pic')"); 
    if($q){
    $message['status'] = "success"; 
    }
    else{
    $message['status'] = "error"; 
    }
    echo json_encode($message); 
}
echo mysqli_error($con); 
?>

Read Data from Database json.php

<?php
include "db.php"; 
$data=array(); 
$q=mysqli_query($con, "SELECT * FROM `products` "); 

while ($row=mysqli_fetch_object($q)){
    $data[]=$row; 
}
echo json_encode($data); 
echo mysqli_error($con); 
?>

Working with Ionic Project

Create new project

ionic start PHPDemo blank
cd PHPDemo
ionic serve

Creating new page for Adding New Product

ionic g page addproduct

Add files in app.module.ts

import { NgModule } from '@angular/core'; 
import { IonicApp, IonicModule } from 'ionic-angular'; 
import { MyApp } from './app.component'; 
import { HomePage } from '../pages/home/home'; 
import { Addproduct } from '../pages/addproduct/addproduct'; 

@NgModule({

    declarations: [
    MyApp, 
    HomePage, 
    Addproduct
    ], 
    imports: [
    IonicModule.forRoot(MyApp)
    ], 
    bootstrap: [IonicApp], 
    entryComponents: [
    MyApp, 
    HomePage, 
    Addproduct
    ], 
    providers: []

})
export class AppModule {}

Adding New Product

working with addproduct.html

<ion-header>
    <ion-navbar>
    <ion-title>Add New Product</ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <ion-list>
    <ion-item>
    <ion-label stacked>Title</ion-label>
    <ion-input type="text" [(ngModel)]="product.title"></ion-input>
    </ion-item>
    <ion-item>
    <ion-label stacked>Description</ion-label>
    <ion-input type="text" [(ngModel)]="product.desc"></ion-input>
    </ion-item>
    <ion-item>
    <ion-label stacked>Price</ion-label>
    <ion-input type="text" [(ngModel)]="product.price"></ion-input>
    </ion-item>
    <ion-item>
    <ion-label stacked>Pic URL</ion-label>
    <ion-input type="text" [(ngModel)]="product.pic"></ion-input>
    </ion-item>
    <button ion-button (click)="insert()">Insert</button>
    </ion-list>
</ion-content>

working with addproduct.ts

import { Component } from '@angular/core'; 
import { NavController, ToastController } from 'ionic-angular'; 
import { Http } from '@angular/http'; 

@Component({
    selector: 'page-addproduct', 
    templateUrl: 'addproduct.html'
})
export class Addproduct {
    product: any = {}; 
    constructor(public navCtrl: NavController, public http: Http, public toast: ToastController) {}

    ionViewDidLoad() {
    console.log('Hello Addproduct Page'); 
    }
    insert(){
    this.product.action = "insert"; 
    this.http.post("http://localhost/ionic2php/product.php", this.product).subscribe(data=>{
    console.log(data); 
    let result = JSON.parse(data["_body"]); 
    if(result.status == "success"){
    this.showToast("Inserted successfully"); 
    }
    else{
    this.showToast("Something went wrong"); 
    }
    }, err=>{
    console.log(err); 
    })
    }

    showToast(message){
    let toast = this.toast.create({
    message:message, 
    duration: 2000
    }); 
    toast.present(); 
    }

}

View Product

To display data from web service.we're going to use home.html with list view

<ion-header>

    <ion-navbar>
        <ion-title>
            Home
        </ion-title>
        <ion-buttons end>
            <button ion-button (click)="goAddNew()">Add</button>
        </ion-buttons>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-list>
        <ion-item *ngFor="let product of productList">
            <ion-avatar item-left>
                <img src="{{product.pic}}">
            </ion-avatar>
            <h2>{{product.title}}</h2>
            <p item-right>$ {{product.price}}</p>
            <p>{{product.desc}}</p>
        </ion-item>
    </ion-list>
</ion-content>

working with home.ts

import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 
import { Addproduct} from '../addproduct/addproduct'
import { Http } from '@angular/http'; 

@Component({
    selector: 'page-home', 
    templateUrl: 'home.html'
})

export class HomePage {
    productList:any; 
    constructor(public navCtrl: NavController, public http: Http) {
    
    }
    ionViewDidLoad(){
    this.getData(); 
    }
    goAddNew(){
    this.navCtrl.push(Addproduct); 
    }
    getData(){
    this.http.get("http://localhost/ionic2php/json.php").subscribe( data => {
    this.productList = JSON.parse(data["_body"]); 
    }, err =>{
    console.log(err); 
    }); 
    }
    
}