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

如何在PHP API中读取Angular DELETE请求的URL ID参数

问题分析与解决方案

问题核心:你在Angular中通过HttpParams将ID作为URL查询参数传递,但PHP端错误地尝试从请求体的JSON内容中读取参数——DELETE请求的查询参数不会出现在php://input中,导致$extract为null,进而触发读取属性的警告。


1. 修正PHP端参数读取逻辑

将delete.php改为从URL查询参数获取ID,而非请求体:

<?php
include('connection.php');

// 从URL查询参数获取idCourse,同时处理参数缺失的情况
$idCourse = $_GET['idCourse'] ?? null;

if ($idCourse) {
    // 使用预处理语句防止SQL注入,禁止直接拼接变量到SQL
    $sql = "DELETE FROM courses WHERE idCourse = ?";
    $stmt = $conn->prepare($sql);
    // 假设idCourse是整数类型,用"i";若为字符串则用"s"
    $stmt->bind_param("i", $idCourse);
    $stmt->execute();
    
    // 返回状态给前端,方便后续处理
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'ID参数缺失']);
}
?>

2. 修正Angular服务中的两处错误

course.service.ts存在两个细节问题:

  • 变量名笔误:curso.idCourse应为course.idCourse
  • filter方法不会修改原数组,需重新赋值给this.courses

修正后的代码:

delete(course: Course): Observable<Course[]> {
    const params = new HttpParams().set('idCourse', course.idCourse!.toString());
    return this.http.delete(`${this.url}delete.php`, { params: params }).pipe(map((res: any) => {
        // 修正变量名,重新赋值过滤后的数组
        this.courses = this.courses.filter((c) => c.idCourse !== course.idCourse);
        return this.courses;
    }))
}

额外注意事项

  • SQL注入风险:原PHP代码直接拼接变量到SQL语句,存在严重安全隐患,必须使用预处理语句(上述代码已修复)。
  • 字段名一致性:检查listOne方法中的course.idCurso,若你的Course接口定义的字段是idCourse,此处属于笔误,会导致删除时ID传递错误。

内容的提问来源于stack exchange,提问作者Kelson Batista

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:45:40