Angular http插入两个数据库记录,其中包括空行

时间:2018-09-21 13:04:59

标签: php mysql angular ionic-framework

我正在开发一个项目,该项目是使用Angular和PHP API和MySQL数据库开发的离子应用程序。

我的项目有两个问题

  1. 此应用程序在数据库中插入两行,其中一行完全为空,另一行具有实际值。

  2. 此应用程序数据库响应返回的观察值始终返回错误,而不是成功。

我尝试了很多方法来解决此问题,但找不到错误点

这是我的视图代码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>

这是我的控制器ts文件

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

      }
    }

这是提供商(服务)ts文件

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

这是我的PHP文件

        <?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

我粘贴了所有代码,因为我无法预测错误的位置。

2 个答案:

答案 0 :(得分:0)

我在这里找到错误

如果我在$ _POST时间为空的标题下使用$ _POST []方法,

因此,我们可以在此类标题之前使用$ _POST来解决该问题,

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

答案 1 :(得分:0)

在设置标头之前使用_POST方法。 否则它将无法获取您的传递值。