0

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

  1. This app insert two row in database one is completely null and other one with actual values.

  2. 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;
      }

enter image description here

I pasted all of code, because I cannot predict where the mistake is.

3
  • you can simply test your variable before pass it into bind_param method : if(isset($request->data->email)){ // do mysql insert } Commented Sep 21, 2018 at 13:13
  • thank you for suggestion sir, this only for security and to confirm right? but this is reason to this matter? Commented Sep 21, 2018 at 13:18
  • 1
    Test variables before use it is a good practice for code quality Commented Sep 21, 2018 at 13:24

2 Answers 2

1

Use _POST method before the headers set. otherwise it will not get your passing values.

Sign up to request clarification or add additional context in comments.

Comments

0

I found the error in here

If i use $_POST[] method under the header that time $_POST give the null,

So escape that issue we can use $_POST before the headers like this

<?php
      $postdata = file_get_contents("php://input",true);
      $request = json_decode($postdata);
      // Sanitize.s
      $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;

      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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.