在构建 RESTful API 时,PHP 函数扮演着至关重要的角色。通过利用这些函数,您可以轻松处理各种 HTTP 请求,返回格式化的 JSON 响应,并管理状态码。
处理 HTTP 请求
生成 JSON 响应
管理状态码
立即学习“PHP免费学习笔记(深入)”;
实战案例
获取所有用户
<?php require 'connect.php'; // Get all users $sql = "SELECT * FROM users"; $result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); // Send JSON response header('Content-Type: application/json'); echo json_encode($result); ?>
创建新用户
<?php require 'connect.php'; // Decode request JSON data $data = json_decode(file_get_contents('php://input'), true); // Create new user $name = $data['name']; $age = $data['age']; $stmt = $conn->prepare("INSERT INTO users (name, age) VALUES (?, ?)"); $stmt->execute([$name, $age]); // Get new user ID $id = $conn->lastInsertId(); // Send JSON response header('Content-Type: application/json'); echo json_encode(['id' => $id]); ?>
更新用户
<?php require 'connect.php'; // Decode request JSON data $data = json_decode(file_get_contents('php://input'), true); // Update user $id = $data['id']; $name = $data['name']; $age = $data['age']; $stmt = $conn->prepare("UPDATE users SET name = ?, age = ? WHERE id = ?"); $stmt->execute([$name, $age, $id]); // Send JSON response header('Content-Type: application/json'); echo json_encode(['success' => true]); ?>
删除用户
<?php require 'connect.php'; // Decode request JSON data $data = json_decode(file_get_contents('php://input'), true); // Delete user $id = $data['id']; $stmt = $conn->prepare("DELETE FROM users WHERE id = ?"); $stmt->execute([$id]); // Send JSON response header('Content-Type: application/json'); echo json_encode(['success' => true]); ?>
以上就是PHP函数在构建RESTful服务的艺术的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号