MVC项目中:点击按钮获取ID并传递至model层muahang.php
MVC架构下点击按钮传递ID到Model层的实现方案
一、前端页面(chocanh.php)传参处理
给按钮绑定目标ID,通过GET或POST请求传递到Controller层:
方案1:GET请求(URL传参)
<!-- 用链接模拟按钮样式 --> <a href="controller.php?action=muahang&id=<?php echo $product_id; ?>" class="btn-buy">立即购买</a>
方案2:POST请求(表单传参,更安全)
<form action="controller.php" method="POST"> <!-- 隐藏域存储商品ID --> <input type="hidden" name="product_id" value="<?php echo $product_id; ?>"> <button type="submit" name="action" value="muahang">立即购买</button> </form>
二、Controller层中转处理
创建或使用现有Controller文件(如controller.php),接收前端参数后调用Model层:
<?php // controller.php if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'muahang') { // 获取并校验ID $product_id = $_REQUEST['product_id'] ?? ''; if (!is_numeric($product_id)) { header("Location: chocanh.php?err=invalid_id"); exit; } // 引入Model层文件 require_once './model/muahang.php'; // 调用Model的业务方法 $buy_result = handle_muahang($product_id); // 根据处理结果跳转页面 if ($buy_result) { header("Location: chocanh.php?msg=buy_success"); } else { header("Location: chocanh.php?err=buy_failed"); } exit; } ?>
三、Model层业务处理(muahang.php)
实现具体的购买逻辑,接收Controller传递的ID:
<?php // model/muahang.php function handle_muahang($product_id) { // 示例:连接数据库执行购买逻辑 $db = mysqli_connect('localhost', 'db_user', 'db_pwd', 'db_name'); if (!$db) { return false; } // 用预处理语句防SQL注入 $stmt = $db->prepare("SELECT * FROM products WHERE id = ?"); $stmt->bind_param("i", $product_id); $stmt->execute(); $product = $stmt->get_result()->fetch_assoc(); if (!$product) { return false; } // 后续执行生成订单、扣减库存等逻辑 // ... return true; } ?>
关键注意事项
- 严格遵循MVC分层原则:View(chocanh.php)不能直接调用Model,必须通过Controller中转,保证代码解耦和可维护性。
- 必须对传递的ID做合法性校验,同时使用预处理语句防止SQL注入,提升安全性。
内容的提问来源于stack exchange,提问作者Hieu Duong
相关产品推荐
相关产品推荐

