我在angular中使用delete方法,并将ID参数发送到PHP REST Api,但它返回null。那么PHP中如何读取参数呢?
delete.php
<?php
include('connection.php');
$extract = json_decode(file_get_contents("php://input"));
$idCourse = $extract->courses->idCourse;
$sql = "DELETE FROM courses WHERE idCourse='$idCourse'";
$conn->query($sql);
?>
course.component.html
<form>
<label for='courseName'>Course name:</label>
<input type="text" name="courseName" [(ngModel)]="course.courseName" />
<label for='coursePrice'>Course price:</label>
<input type="text" name="coursePrice" [(ngModel)]="course.coursePrice" />
<button (click)="register(this.course)">Register</button>
<button (click)="update(this.course)">Update</button>
<button (click)="delete(this.course)">Delete</button>
</form>
<table border="1">
<tr>
<td>Course Name</td>
<td>Price</td>
</tr>
<tr *ngFor='let course of courses'>
<td>{{ course.courseName }}</td>
<td>{{ course.coursePrice }}</td>
<td><button (click)="listOne(course)">Select course</button></td>
</tr>
</table>
张清单()
listOne(course: Course) {
this.course.idCourse = course.idCurso;
this.course.courseName = course.courseName;
this.course.coursePrice = course.coursePrice;
}
course.component.ts
delete(course: Course) {
this.courseService.delete(course).subscribe((res: Course[]) => {
this.courses = res;
this.course = new Course();
this.list();
});
}
course.service.ts
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.filter((c) => c.idCourse !== curso.idCourse);
return this.courses;
}))
}
PHP错误
[Wed Nov 9 18:13:12 2022] PHP Warning: Attempt to read property "courses" on null in /var/www/api/backend/delete.php on line 5
[Wed Nov 9 18:13:12 2022] PHP Warning: Attempt to read property "idCourses" on null in /var/www/api/backend/delete.php on line 5
PS:其他方法,如POST PUT和GET使用类似的JSON读取方法在PHP (json_decode)工作完美。只有DELETE方法返回null。
您正在将QueryParamidCourse
添加到请求中。
在你的php代码中,你使用$extract = json_decode(file_get_contents("php://input"));
,它将读取请求体(而不是查询参数))并解析它。因为你没有从angular传递请求体(可能不应该,因为这是一个DELETE
调用),你应该在服务器端读取实际的查询参数。
在PHP中有不同的选项来实际读取查询字符串(参见这里:获取URL查询字符串参数),但这里有一个示例:
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
$idCourse = $queries['idCourse']
$sql = "DELETE FROM courses WHERE idCourse='$idCourse'";
$conn->query($sql);
<<p>大警告/strong>如果您直接将查询参数传递给SQL查询,则基本上使您的应用程序容易受到SQL注入的攻击。您应该查看https://www.php.net/manual/en/security.database.sql-injection.php以了解如何避免这种情况。