Interact Ionic (Angular 2) with MySQL database and PHP Backend


Hello everybody,

I’m french so sorry if my english is not perfect.

I’m developping an Ionic web app using Angular 2 and currently, i’m working on the registration form.

I explain you my problem, the app will permit users to share some products that could be buy by other users. So, the content of the application will be managed by users. That means that there is also a database to manage.

I moved over a mysql database with a php backend.

And i’m unable to send post data to my database with php script.
Also i want to know if there is a better solution and easier than using mysql and php.

This is my programm :

register.html :

  Generated template for the RegisterPage page.

  See for more info on
  Ionic pages and navigation.

<ion-content padding class="login-content">
  <div class="login-box">
    <form (ngSubmit)="register()" #registerForm="ngForm">
          <ion-list inset>
              <ion-input type="text" placeholder="Email" name="email" [(ngModel)]="" required></ion-input>

              <ion-input type="password" placeholder="Password" name="password" [(ngModel)]="registerCredentials.password" required></ion-input>

        <ion-col class="signup-col">
          <button ion-button class="submit-btn" full type="submit" [disabled]="!registerForm.form.valid">Register</button>

register component :

import { Component } from '@angular/core';
import {AlertController, NavController} from 'ionic-angular';
import {AuthService} from '../../services/auth-service';

 * Generated class for the RegisterPage page.
 * See for more info
 * on Ionic pages and navigation.

  selector: 'page-register',
  templateUrl: 'register.html',
export class RegisterPage {
  createSuccess = false;
  registerCredentials = { email: '', password: '' };

  constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController) { }

  public register() {
    this.auth.register(this.registerCredentials).subscribe(success => {
          if (success) {
            this.createSuccess = true;
            this.showPopup("Success", "Account created.");
          } else {
            this.showPopup("Error", "Problem creating account.");
        error => {
          this.showPopup("Error", error);

  showPopup(title, text) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: text,
      buttons: [
          text: 'OK',
          handler: data => {
            if (this.createSuccess) {

authentification service :

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import {User} from '../models/user/user';
import {Http, Headers} from "@angular/http";

export class AuthService {
    currentUser: User;

    constructor(private http: Http) { }

    public login(credentials) {
        if ( === null || credentials.password === null) {
            return Observable.throw("Please insert credentials");
        } else {
            return Observable.create(observer => {
                // At this point make a request to your backend to make a real check!
                let access = (credentials.password === "pass" && === "email"); // test
                this.currentUser = new User('email', 'pass');

    public register(credentials) {
        if ( === null || credentials.password === null) {
            return Observable.throw("Please insert credentials");
        } else {
            // At this point store the credentials to your backend!
            return Observable.create(observer => {
                const url = "http://localhost:8080/add.php";
                const body = {email:, password: credentials.password};
                const headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                /*const obj = {email:, password: credentials.password};
                const body = 'data=' + JSON.stringify(obj);*/
      , JSON.stringify(body), {headers: headers})
                    .map(res => res.json())
                    .subscribe(data =>
                        console.log(data)//you can format the response from your server
               );//and then return data

    public getUserInfo() : User {
        return this.currentUser;

    public logout() {
        return Observable.create(observer => {
            this.currentUser = null;

User model

export class User {
    email: string;
    password: string;

    constructor(email: string, password: string) { = email;
        this.password = password;

My php file add.php :

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

$user="root"; //identifiant
$password=""; //mot de passe

try {
    $pdo=new PDO($host, $user, $password);
    $pdo->exec('SET NAMES UTF8');
} catch (Exception $e) {
    die('Problème : ' . $e->getMessage());

$formData = json_decode(file_get_contents('php://input'));
foreach ($formData as $key=>$value) {

$req=$pdo->prepare("INSERT INTO user(emailAddress, password) VALUES (:emailAddress, :password)");
$req->execute(array("emailAddress" => $_POST['email'], "password" => $_POST['password']));

echo $req;

Have you ever been confronted to this kind of problem ?

Thanks in advance



Hello Asad,

I don't debug your code, simply because there are tons of tutorials on the net on how to create a php file to receive uploads from Ionic 2/3, just check a bit more please.

On other side note and because you ask, yes there are plenty of easier solutions, AWS could be one, I chose Firebase in my app (still in beta), and it works like a charm.

Again, if you must do with entreprise database and file storage, there are tons of tutorials, dig more around the native file plugin, often your php "receiver" file must accept the whole body as http call (GET mode), otherwise the file transfer will fail.

Hope it helps,


This is just my personal opinion, but I believe absolutely anything is better than either PHP or MySQL. PHP has always been a horrific language, and once Oracle bought MySQL they absolutely ruined it.

That being said, you should almost never need to explicitly instantiate Observables, and certainly not here.

Most importantly, do not store cleartext passwords on your server. That gets people sued.