I am working on a project which is Ionic application developed with Angular and PHP API and MySQL database.
I have two problem in my project
This app insert two row in database one is completely null and other one with actual values.
This app database response return observable always return to the error not for success.
I tried so many ways to solved this but I couldn't find the error point
Here is my view codes html:
<ion-content padding>
<!--class="items-middle" text-center-->
<ion-list>
{{ responseTxt | json }}
{{ errorTxt | json }}
<!-- use the [formGroup] directive to tell Angular that we want to use the registrationForm as the "FormGroup" for this form: -->
<form [formGroup]="registrationForm" (ngSubmit)="addMember()">
<ion-item>
<ion-label floating>Full Name</ion-label>
<ion-input type="text" [(ngModel)]="reg.userName" formControlName="userName"></ion-input>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.userName.touched && (registrationForm.controls.userName.invalid ||
registrationForm.controls.userName.hasError('pattern'))">Enter valid username.</p>
<ion-item>
<ion-label color="ligh-grey" floating>Email</ion-label>
<ion-input type="email" [(ngModel)]="reg.email" formControlName="email"></ion-input>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.email.touched && (registrationForm.controls.email.invalid ||
registrationForm.controls.email.hasError('pattern'))">Enter valid email.</p>
<ion-item>
<ion-label color="ligh-grey" floating>Birth of Date</ion-label>
<ion-datetime displayFormat="DD/MM/YYYY" formControlName="dob" [(ngModel)]="reg.dob" pickerFormat="MMMM DD YYYY" min="1940" max="{{year}}">
</ion-datetime>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.dob.touched && (registrationForm.controls.dob.invalid)">Enter your Date of Birth</p>
<ion-item>
<ion-label color="ligh-grey" floating>Phone Number</ion-label>
<ion-input type="number" formControlName="phone" [(ngModel)]="reg.phone" pattern="[0-9]*"></ion-input>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.phone.touched && (registrationForm.controls.phone.invalid ||
registrationForm.controls.phone.hasError('pattern'))">Enter valid phone number.</p>
<ion-item>
<ion-label color="ligh-grey" floating>Address</ion-label>
<ion-input type="text" formControlName="address" [(ngModel)]="reg.address"></ion-input>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.address.touched && (registrationForm.controls.address.invalid)">Enter valid address.</p>
<ion-item class="job_status">
<ion-label color="ligh-grey" floating>Job Status (Position)</ion-label>
<ion-input type="text" formControlName="jobStatus" [(ngModel)]="reg.jobStatus"></ion-input>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.jobStatus.touched && (registrationForm.controls.jobStatus.invalid)">Enter valid job status.</p>
<ion-item>
<ion-label>Job Sector</ion-label>
<ion-select formControlName="jobSector" [(ngModel)]="reg.jobSector">
<ion-option value="Government">Government</ion-option>
<ion-option value="Private">Private</ion-option>
</ion-select>
</ion-item>
<p class="text-danger" *ngIf="registrationForm.controls.jobSector.touched && (registrationForm.controls.jobSector.invalid)">Choose a job sector.</p>
<!--<input type="checkbox" formControlName="isTosRead">-->
<!-- We can check if our form is valid: -->
<ion-buttons padding-top>
<button ion-button full round type="submit" [disabled]="!registrationForm.valid">SIGNUP</button>
</ion-buttons>
</form>
</ion-list>
This is my controller ts file
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Reg } from "./Reg";
import { NetworkEngineProvider } from "../../providers/network-engine/network-engine";
@IonicPage()
@Component({
selector: 'page-registration',
templateUrl: 'registration.html',
})
export class RegistrationPage {
registrationForm: FormGroup; // Form group build object
reg = new Reg('','','','','','',''); // create Reg class object
year = null;
currentTime = null;
responseTxt : any;
errorTxt : any;
constructor(public navCtrl: NavController, public navParams: NavParams, private fb: FormBuilder, private network : NetworkEngineProvider) {
// isTosRead: new FormControl(false, [Validators.requiredTrue])
/* set form controls and validations */
this.registrationForm = this.fb.group({
userName: [
null, Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])
],
email: [
null, Validators.compose([Validators.required, Validators.email, Validators.minLength(4)])],
dob: [
null, Validators.compose([Validators.required])],
phone: [
null, Validators.compose([Validators.required, Validators.pattern('^7|0|(?:\\+94)[0-9]{9,10}$'), Validators.minLength(9), Validators.maxLength(10)])],
address: [
null, Validators.compose([Validators.required, Validators.minLength(9), Validators.maxLength(255)])],
jobStatus: [
null, Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(50)])],
jobSector: [
null, Validators.compose([Validators.required])],
});
this.getYear();
}
/* get year and deduct 16 from that year */
getYear(){
this.currentTime = new Date();
this.year = this.currentTime.getFullYear();
this.year = this.year - 16;
}
/* ================ register new user ================= */
addMember(){
this.network.regUser(this.reg).subscribe(
(data) => {
this.responseTxt = "Your registration is success";
console.log('success');
},
(err) => this.errorTxt = err
);
}
}
This is the provider(service) ts file
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Reg } from "../../pages/registration/Reg";
import {Observable} from "rxjs";
import {catchError, map} from "rxjs/operators";
import {_throw} from 'rxjs/observable/throw';
import { RegistrationPage } from "../../pages/registration/registration";
@Injectable()
export class NetworkEngineProvider {
baseUrl = 'http://localhost/api';
registrations: Reg[];
obj : RegistrationPage;
constructor(public http: HttpClient) {
}
// The method which actually dealing with remote server php file and that return promise
readTableData() : Promise<any>{
let url = "http://localhost/ctest/ionic/read.php";
let request = this.http.get(url);
return request.toPromise();
}
//regUser(reg : Reg): Promise<any>{
// return this.http.post(`${this.baseUrl}/registration`, { data: reg })
// .pipe(map((res) => {
// this.registrations.push(res['data']);
// return this.registrations;
// }),
// catchError(this.handleError(HttpErrorResponse));
//catchError(this.handleError));
//let request = this.http.post(`${this.baseUrl}/registration`,{ data: reg });
//return request.toPromise();
//}
regUser(reg : Reg): Observable<any> {
return this.http.post(`${this.baseUrl}/registration.php`, { data: reg })
.pipe(map((res) => {
return res;
}))
}
}
And this is my PHP file
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hoba";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn, "utf8");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
// Sanitize.
$userName = $request->data->userName;
$email = $request->data->email;
$dob = $request->data->dob;
$phone = $request->data->phone;
$address = $request->data->address;
$jobStatus = $request->data->jobStatus;
$jobSector = $request->data->jobSector;
// Store.
$stmt = $conn->prepare("INSERT INTO user_profile (user_name,email,dob,address,phone_number,job_status,gov_or_pvt)
VALUES (?,?,?,?,?,?,?)");
$stmt->bind_param("sssssss", $userName, $email,$dob,$phone,$address,$jobStatus,$jobSector);
if ($stmt->execute())
{
//echo http_response_code(201);
echo "New record created successfully";
} else {
//echo http_response_code(422);
echo "Some error";
// echo "Error: " . $sql . "<br>" . $conn->error;
}
I pasted all of code, because I cannot predict where the mistake is.

if(isset($request->data->email)){ // do mysql insert }