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

如何获取选中按钮对应食谱的ID并插入数据库?

获取点击按钮对应食谱ID并插入数据库的解决方案

我来帮你搞定这个问题!这种循环渲染条目后获取对应ID的需求非常常见,分几步就能轻松实现:

1. 后端渲染条目时,给按钮绑定食谱ID

假设你用PHP做后端渲染(其他后端语言逻辑完全类似),在while循环输出每个食谱条目时,把食谱ID存在按钮的data-*属性里——这是最规范且安全的绑定方式:

<?php
// 假设你的查询结果存在$recipes数组中
while ($recipe = mysqli_fetch_assoc($result)) {
?>
<div class="recipe-item">
  <h3><?php echo htmlspecialchars($recipe['name']); ?></h3>
  <p><?php echo htmlspecialchars($recipe['description']); ?></p>
  <img src="<?php echo htmlspecialchars($recipe['image_url']); ?>" alt="<?php echo htmlspecialchars($recipe['name']); ?>">
  <!-- 核心:用data-recipe-id存储当前食谱的ID -->
  <button class="save-recipe-btn" data-recipe-id="<?php echo $recipe['id']; ?>">保存食谱</button>
</div>
<?php
}
?>

2. 前端监听点击,获取ID并发送请求

用JavaScript给所有按钮绑定点击事件,从按钮的data属性中拿到对应食谱ID,再通过AJAX把ID传给后端接口完成插入:

// 获取所有"保存食谱"按钮
const saveButtons = document.querySelectorAll('.save-recipe-btn');

saveButtons.forEach(button => {
  button.addEventListener('click', function() {
    // 从data属性中提取食谱ID
    const recipeId = this.dataset.recipeId;
    
    // 发送POST请求到后端接口
    fetch('save-recipe.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // 如果网站有登录功能,记得加CSRF令牌防攻击:
        // 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
      },
      body: `recipe_id=${encodeURIComponent(recipeId)}`
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('食谱已成功保存到数据库!');
      } else {
        alert('保存失败,请重试');
      }
    })
    .catch(error => {
      console.error('请求出错:', error);
      alert('网络错误,请稍后再试');
    });
  });
});

3. 后端处理插入逻辑(以PHP为例)

创建save-recipe.php文件,接收前端传来的ID,用预处理语句执行数据库插入(重点防SQL注入):

<?php
// 连接数据库(这里用mysqli,PDO逻辑类似)
$conn = mysqli_connect('localhost', '你的用户名', '你的密码', '你的数据库名');

if (!$conn) {
  die(json_encode(['success' => false, 'error' => '数据库连接失败']));
}

// 校验并获取前端传来的ID
$recipeId = isset($_POST['recipe_id']) ? intval($_POST['recipe_id']) : 0;

if ($recipeId <= 0) {
  echo json_encode(['success' => false, 'error' => '无效的食谱ID']);
  exit;
}

// 用预处理语句插入,彻底防止SQL注入
$stmt = $conn->prepare("INSERT INTO saved_recipes (recipe_id) VALUES (?)");
$stmt->bind_param("i", $recipeId);

if ($stmt->execute()) {
  echo json_encode(['success' => true]);
} else {
  echo json_encode(['success' => false, 'error' => $stmt->error]);
}

$stmt->close();
mysqli_close($conn);
?>

关键注意事项

  • 防SQL注入:必须用预处理语句,绝对不能直接把用户传来的ID拼进SQL语句里。
  • 数据校验:后端一定要对接收的ID做合法性校验(比如是否为正整数),避免无效数据入库。
  • CSRF防护:如果网站有用户登录功能,记得添加CSRF令牌,避免跨站请求伪造攻击。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:51:25