在 Debian 上用 LAMP 搭建 API 接口

一 环境准备与安装
二 数据库与示例数据
三 编写第一个 API 接口
$method = $_SERVER[‘REQUEST_METHOD’] ?? ‘GET’;$id = $_GET[‘id’] ?? null;
// 连接数据库$conn = new mysqli(‘localhost’, ‘myuser’, ‘mypassword’, ‘myapi’);if ($conn->connect_error) {http_response_code(500);echo json_encode([‘error’ => ‘Database connection failed’]);exit;}$conn->set_charset(‘utf8mb4’);
// 处理请求if ($method === ‘GET’) {if ($id) {$stmt = $conn->prepare(‘SELECT id, name, email FROM users WHERE id = ?’);$stmt->bind_param(‘i’, $id);$stmt->execute();$res = $stmt->get_result();$user = $res->fetch_assoc();echo $user ? json_encode($user) : json_encode([‘error’ => ‘Not found’], JSON_UNESCAPED_UNICODE);} else {$res = $conn->query(‘SELECT id, name, email FROM users ORDER BY id DESC’);echo json_encode($res->fetch_all(MYSQLI_ASSOC));}} elseif ($method === ‘POST’) {$input = json_decode(file_get_contents(‘php://input’), true);$name= trim($input[‘name’] ?? ‘’);$email = trim($input[‘email’] ?? ‘’);if (!$name || !$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {http_response_code(400);echo json_encode([‘error’ => ‘Invalid input’]);exit;}$stmt = $conn->prepare(‘INSERT INTO users (name, email) VALUES (?, ?)’);$stmt->bind_param(‘ss’, $name, $email);if ($stmt->execute()) {http_response_code(201);echo json_encode([‘id’ => $conn->insert_id, ‘name’ => $name, ‘email’ => $email]);} else {http_response_code(500);echo json_encode([‘error’ => ‘Insert failed’]);}} else {http_response_code(405);echo json_encode([‘error’ => ‘Method not allowed’]);}$conn->close();?>
四 安全与优化
五 进阶方案与部署
借助RubyGnome2库进行GTK下的Ruby GUI编程的基本方法
哑巴模型Jev使用实用指南:运行机制、原语定义、运行时环境配置及业务场景实用指南
编写Ruby脚本来对Twitter用户的数据进行深度挖掘
从零搭建自己的Codex Plugin Marketplace的实践指南实用指南
如何解决PHPExcel不兼容php7.4版本
thinkphp使用url请求调用ThinkApi天气教程【图文详解】