You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Angular和PHP发送Post请求无法向服务器传递数据

Angular POST请求无法插入MySQL数据问题排查

我尝试通过Angular服务发送POST请求到PHP文件,在XAMPP的MySQL中插入数据,但调用服务函数后数据库没有新增数据。以下是相关代码:

Angular服务代码

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
import { Epidemiologiques, Patient, Biologiques,Traitement, Cliniques } from './patient';

@Injectable({
  providedIn: 'root'
})
export class DonneesPatientService {
   private baseUrl = "http://localhost:8080/gestipatient.php";
  constructor(private http: HttpClient) { }

  postPatient(patient:Patient){
   
    this.http.post(`${this.baseUrl}?func=Ajouter_Patient&nom=${patient.nomPrenom}&cin=${patient.cin}
    &profession=${patient.proffesion}&dateNai=${patient.DateNa}&sexe=${patient.sexe}&res=${patient.Res}
    &ville=${patient.Ville}&province=${patient.Province}&tele=${patient.Tele}`,
    { }).subscribe({ next: (response) => { /* Success action */ } });
  }
}

gestipatient.php代码

<?php
require ("patient.php");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Origin: *');
$medecin =new medecin(0,"","","","");

if (isset($_GET['func'])) {
    $func = $_GET['func'] ;
} else {
    // Fallback behaviour goes here
}

extract( $_GET);
extract( $_POST);
if($func ='Ajouter_Patient') $medecin->addPatient($nom,$cin,$profession,$dateNai,$sexe,$res,$ville,$province,$tele);

?>

patient.php代码

<?php 
session_start();
function connect(){
    $con =null;
    try{
        $con=new PDO("mysql:host=localhost;dbname=chu","root",""
    }catch(Exception $e){}
    return $con;
}

class medecin{
    public $idmed;
    public $nomed;
    public $prenommed;
    public $login;
    public $motdepasse; 
    public function __construct($i,$n,$p,$l,$m)
    {
        $this->idmed=$i;
        $this->nomed=$n;
        $this->prenommed=$p;
        $this->login=$l;
        $this->motdepasse=$m;
    }
    public function addPatient($nom,$cin,$profession,$datedenaissance,$sexe,$residance,$ville,$province,$tele)
    {
        $result;
        $con=connect();
        if($con!=null)
        {
        $con->query("insert into `patient`(`Nom`,`Prenom`,`CIN`,`Profession`,`Date de naissance`,`Sexe`,`Residance habituelle`,`Ville `,`Province`,`Telephone`)
        values('" . $nom . "','" . $nom . "','" . $cin . "','" . $profession . "', '" . $datedenaissance . "','" . $sexe . "','" . $residance . "', '" . $ville . "','" . $province . "','" . $tele . "');");
        $result = array("result" => "Success");
        echo json_encode($result);
        }else{
        $result = array("result" => "Failure");
        echo json_encode($result);
        }
        return -1;
    }
}
class patient{
    public $idp;
    public $nom;
    public $prenom;
    public $cin;
    public $profession;
    public $datedenaissance;
    public $sexe;
    public $residance;
    public $ville;
    public $province;
    public $tele;
  
    public function __construct($i,$n,$p,$c,$pr,$d,$s,$r,$v,$pro,$t)
    {
        $this->idp=$i;
        $this->nom=$n;
        $this->prenom=$p;
        $this->cin=$c;
        $this->profession=$pr;
        $this->datedenaissance=$d;
        $this->sexe=$s;
        $this->residance=$r;
        $this->ville=$v;
        $this->province=$pro;
        $this->tele=$t;
       
    }

}
?>

问题排查与修复方案

1. PHP条件判断语法错误

gestipatient.php中if($func ='Ajouter_Patient')是赋值操作,不是比较逻辑,导致无论func参数是什么都会执行添加逻辑,同时可能覆盖func变量。修改为严格比较:

if($func === 'Ajouter_Patient') 
    $medecin->addPatient($nom,$cin,$profession,$dateNai,$sexe,$res,$ville,$province,$tele);

2. 数据库连接语法错误

patient.php的connect()函数中,PDO初始化语句缺少闭合括号和分号,导致无法建立数据库连接,同时添加错误模式便于调试:

function connect(){
    $con = null;
    try{
        $con = new PDO("mysql:host=localhost;dbname=chu","root","");
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(Exception $e){
        echo "连接失败: " . $e->getMessage();
    }
    return $con;
}

3. SQL插入逻辑错误与安全问题

addPatient()方法中,将$nom同时插入Nom和Prenom字段导致数据错误,且直接拼接SQL存在SQL注入风险,改用预处理语句:

public function addPatient($nom,$cin,$profession,$datedenaissance,$sexe,$residance,$ville,$province,$tele)
{
    $result;
    $con = connect();
    if($con != null)
    {
        $sql = "INSERT INTO `patient`(`Nom`,`Prenom`,`CIN`,`Profession`,`Date de naissance`,`Sexe`,`Residance habituelle`,`Ville`,`Province`,`Telephone`)
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $con->prepare($sql);
        // 若Angular传递的是全名,可拆分姓名:list($nomPart, $prenomPart) = explode(' ', $nom);
        $stmt->execute([$nom, "默认名", $cin, $profession, $datedenaissance, $sexe, $residance, $ville, $province, $tele]);
        
        $result = array("result" => "Success");
        echo json_encode($result);
    }else{
        $result = array("result" => "Failure");
        echo json_encode($result);
    }
    return -1;
}

4. Angular请求参数传递规范修正

当前POST请求将参数放在URL查询字符串中,不符合POST规范,改为请求体传参,并修正变量拼写错误:

postPatient(patient: Patient){
    const body = {
        nom: patient.nomPrenom,
        cin: patient.cin,
        profession: patient.profession, // 修正拼写:proffesion -> profession
        dateNai: patient.DateNa,
        sexe: patient.sexe,
        res: patient.Res,
        ville: patient.Ville,
        province: patient.Province,
        tele: patient.Tele
    };
    this.http.post(`${this.baseUrl}?func=Ajouter_Patient`, body)
        .subscribe({ 
            next: (response) => { console.log('插入成功:', response); },
            error: (err) => { console.error('请求失败:', err); } // 增加错误日志
        });
}

同时修改PHP参数接收方式,避免变量覆盖:

if($func === 'Ajouter_Patient'){
    $nom = $_POST['nom'] ?? '';
    $cin = $_POST['cin'] ?? '';
    $profession = $_POST['profession'] ?? '';
    $dateNai = $_POST['dateNai'] ?? '';
    $sexe = $_POST['sexe'] ?? '';
    $res = $_POST['res'] ?? '';
    $ville = $_POST['ville'] ?? '';
    $province = $_POST['province'] ?? '';
    $tele = $_POST['tele'] ?? '';
    
    $medecin->addPatient($nom,$cin,$profession,$dateNai,$sexe,$res,$ville,$province,$tele);
}

5. 调试建议

  • 查看浏览器开发者工具Network标签,确认POST请求的状态码、参数和响应内容;
  • 在PHP代码中添加日志输出,检查参数是否正确接收、数据库连接状态;
  • 启用MySQL查询日志,确认插入语句是否执行。

内容的提问来源于stack exchange,提问作者Omar El ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:51:56