【问题标题】:Angular http insert two database record including null rowAngular http插入两个数据库记录,包括空行
【发布时间】:2019-02-25 21:43:57
【问题描述】:

我正在开发一个项目,它是使用 Angular 和 PHP API 以及 MySQL 数据库开发的 Ionic 应用程序。

我的项目有两个问题

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

  2. 此应用程序数据库响应返回 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;
      }

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

【问题讨论】:

  • 您可以简单地测试您的变量,然后再将其传递给 bind_param 方法:if(isset($request-&gt;data-&gt;email)){ // do mysql insert }
  • 谢谢您的建议先生,这只是为了安全和确认对吗?但这就是这件事的原因吗?
  • 使用前测试变量是提高代码质量的好习惯

标签: php mysql angular ionic-framework


【解决方案1】:

在设置标题之前使用 _POST 方法。 否则它不会得到你的传递值。

【讨论】:

    【解决方案2】:

    我在这里发现了错误

    如果我在标题下使用 $_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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      相关资源
      最近更新 更多