Unable to fetch records from Mysql using ionic

Hello Everyone

I am using CRUD with PHP and Mysql example. My app insert the record successfully, but unable to to read the records. When i register new user it successfully insert user in login table. But when i try to login it does not read records from Mysql. My code is this.

post-provider.ts
import { Injectable } from ‘@angular/core’;

import { Http, Headers, RequestOptions } from ‘@angular/http’;

import ‘rxjs/add/operator/map’;

@Injectable()

export class PostProvider {

server: string = 'https://localhost/ionic4login/server_api/';

constructor(public http: Http) {

}

    postData(body, file){

    let type = 'application/json; charset=utf-8';

    let headers = new Headers({ 'Content-Type': type });

    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.server + file, JSON.stringify(body), options)

    .map(res => res.json());

}

}

login.page.ts
import { Component, OnInit } from ‘@angular/core’;

import { Router } from ‘@angular/router’;

import { ToastController } from ‘@ionic/angular’;

import { PostProvider } from ‘…/…/providers/post-provider’;

import { Storage } from ‘@ionic/storage’;

@Component({

selector: ‘app-login’,

templateUrl: ‘./login.page.html’,

styleUrls: [’./login.page.scss’],

})

export class LoginPage implements OnInit {

username: string = ‘’;

password: string = ‘’;

constructor(

private router: Router,

public toastController: ToastController,

private postPvdr: PostProvider,

private storage: Storage,

) { }

ngOnInit() {

}

formRegister() {

this.router.navigate(['/register']);

}

async proseslogin() {

if (this.username != '' && this.password != '') {

  let body = {

    username: this.username,

    password: this.password,

    aksi: 'login'

  };

  this.postPvdr.postData(body, 'file_aksi.php').subscribe(async data => {

   var alertpesan = data.msg;

   if (data.success) {

     this.storage.set('session_storage', data.result);

     this.router.navigate(['/customer']);

     const toast = await this.toastController.create({

      message: 'Welcome!',

      duration: 2000

     });

     toast.present();

   } else {

     const toast = await this.toastController.create({

       message: alertpesan,

       duration: 2000

     });

     toast.present();

   }

 });

} else {

  const toast = await this.toastController.create({

    message: 'Username or password invalid',

    duration: 2000

  });

  toast.present();

}

this.username = '';

this.password = '';

}

}

login.page.html

<ion-title>login</ion-title>
<ion-item>

  <ion-label position="floating">Username</ion-label>

  <ion-input [(ngModel)]="username"></ion-input>

</ion-item>



<ion-item>

  <ion-label position="floating">Password</ion-label>

  <ion-input type="password" [(ngModel)]="password"></ion-input>

</ion-item>
<ion-button expand="block" shape="round" (click)="proseslogin()" >Sign In</ion-button>

<ion-button expand="block" shape="round" (click)="formRegister()">Register</ion-button>

file_aksi.php

<?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization'); header('Content-Type: application/json; charset=UTF-8'); define('DB_NAME', 'ionic4login'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $postjson = json_decode(file_get_contents('php://input'), true); $today = date('Y-m-d'); if($postjson['aksi'] == "add_register") { $password = md5($postjson['password']); $query = mysqli_query($mysqli, "INSERT INTO login SET full_name = '$postjson[full_name]', phone_number = '$postjson[phone_number]', username = '$postjson[username]', password = '$postjson[password]' "); // password = '$password' if($query) $result = json_encode(array('success' =>true)); else $result = json_encode(array('success' => false, 'msg'=>'error , please try again')); echo $result; } elseif($postjson['aksi'] == "login") { echo "hello"; $password = md5($postjson['password']); $query = mysqli_query($mysqli, "SELECT * FROM login WHERE username='$postjson[username]' AND password='$password' "); $check = mysqli_num_rows($query); if($check>0){ $data = mysqli_fetch_array($query); $datauser = array( 'user_id' => $data['user_id'], 'full_name' => $data['full_name'], 'phone_number' => $data['phone_number'], 'username' => $data['username'], 'password' => $data['password'] ); if($query) $result = json_encode(array('success' =>true, 'result'=>$datauser)); else $result = json_encode(array('success' => false, 'msg'=>'error, please try again')); }else{ $result = json_encode(array('success' => false, 'msg'=>'unregister account')); } echo $result; } if($postjson['aksi']=='add'){ $query = mysqli_query($mysqli, "INSERT INTO master_customer SET name_customer = '$postjson[name_customer]', desc_customer = '$postjson[desc_customer]', created_at = '$today' "); $idcust = mysqli_insert_id($mysqli); if($query) $result = json_encode(array('success'=>true, 'customerid'=>$idcust)); else $result = json_encode(array('success'=>false)); echo $result; } elseif($postjson['aksi']=='getdata'){ $data = array(); $query = mysqli_query($mysqli, "SELECT * FROM master_customer ORDER BY customer_id DESC LIMIT $postjson[start],$postjson[limit]"); while($row = mysqli_fetch_array($query)){ $data[] = array( 'customer_id' => $row['customer_id'], 'name_customer' => $row['name_customer'], 'desc_customer' => $row['desc_customer'], 'created_at' => $row['created_at'], ); } if($query) $result = json_encode(array('success'=>true, 'result'=>$data)); else $result = json_encode(array('success'=>false)); echo $result; } elseif($postjson['aksi']=='update'){ $query = mysqli_query($mysqli, "UPDATE master_customer SET name_customer='$postjson[name_customer]', desc_customer='$postjson[desc_customer]' WHERE customer_id='$postjson[customer_id]' "); if($query) $result = json_encode(array('success'=>true, 'result'=>'success')); else $result = json_encode(array('success'=>false, 'result'=>'error')); echo $result; } elseif($postjson['aksi']=='delete'){ $query = mysqli_query($mysqli, "DELETE FROM master_customer WHERE customer_id='$postjson[customer_id]' "); if($query) $result = json_encode(array('success'=>true, 'result'=>'success')); else $result = json_encode(array('success'=>false, 'result'=>'error')); echo $result; } ?>

PHP gives me a massive migraine, so I’ll just note that you don’t need to (and shouldn’t be, because it obscures the important things about your code):

  • manually stringify objects getting passed to HttpClient
  • manually define content type
  • manually do anything with headers or options here
  • manually deserialize

Your entire postData can be just:

return this.http.post(this.server + file, body);