插入两个包含空行的数据库记录

vwoqyblh  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(327)

我正在从事一个项目,这是离子应用程序开发的Angular 和PHPAPI和mysql数据库。
我的项目有两个问题
这个应用程序在数据库中插入两行,一行是完全空的,另一行是实际值。
此应用程序数据库响应返回observable始终返回到错误而不是成功。
我尝试了很多方法来解决这个问题,但是我找不到错误点
以下是我的视图代码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;
      }


我粘贴了所有的代码,因为我无法预测错误在哪里。

vxf3dgd4

vxf3dgd41#

我在这里发现了错误
如果我在time$\u post给出null的头下使用$\u post[]方法,
为了避免这个问题,我们可以在像这样的标题之前使用$\u 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');
olmpazwi

olmpazwi2#

在设置头之前使用\u post方法。否则它将无法获得您的传递值。

相关问题