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


#1

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 http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>
  <ion-navbar>
    <ion-title>Registration</ion-title>
  </ion-navbar>
</ion-header>


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

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

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

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 http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@Component({
  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) {
              this.nav.popToRoot();
            }
          }
        }
      ]
    });
    alert.present();
  }
}

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";

@Injectable()
export class AuthService {
    currentUser: User;


    constructor(private http: Http) { }

    public login(credentials) {
        if (credentials.email === 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" && credentials.email === "email"); // test
                this.currentUser = new User('email', 'pass');
                observer.next(access);
                observer.complete();
            });
        }
    }

    public register(credentials) {
        if (credentials.email === 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: credentials.email, password: credentials.password};
                const headers = new Headers();
                headers.append('Content-Type', 'application/x-www-form-urlencoded');
                /*const obj = {email: credentials.email, password: credentials.password};
                const body = 'data=' + JSON.stringify(obj);*/
                this.http.post(url, JSON.stringify(body), {headers: headers})
                    .map(res => res.json())
                    .subscribe(data =>
                    {
                        console.log(data)//you can format the response from your server
                        observer.next(data );//and then return data
                        observer.complete();
                    });
            });
        }
    }

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

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

User model

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

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

My php file add.php :

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

$host="mysql:host=localhost;dbname=shaker";
$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) {
    $_POST[$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

Asad


#2

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,


#3

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.