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

如何获取PHP循环生成的submit按钮对应的指定商品数据

问题原因

  • 页面缺少<form>表单标签,点击submit按钮不会触发POST请求提交,这是if(isset($_POST['submit']))检测不生效的核心原因
  • 循环生成的所有提交按钮未和对应商品ID绑定,提交时无法区分被点击按钮对应的商品

解决方案

推荐使用每个商品对应独立表单的方案实现,逻辑简单无需额外处理,修改后的可用代码如下:

<?php
require_once '../includes/header.php';
require_once '../includes/connection.php';

// POST处理逻辑放在页面最顶部,避免输出内容后操作报错
if(isset($_POST['submit']))
{
    $id = $_POST['shoe_id'];
    $shoe_name = $_POST['shoe_name'];
    // 此处编写你的加购物车逻辑,例如写入SESSION、存入购物车表等
    // 操作完成后可刷新页面避免重复提交:
    // header("Location: ".$_SERVER['PHP_SELF']);
    // exit;
}

// 从数据库读取商品数据
$sql="select * from shoes";
$result = $con->query($sql);
?>

<html>
<main role="main">
<section class="sec-intro" role="section">
      <h1>Products</h1>
</section>

<section class="sec-boxes" role="section">
<?php
while ($row = $result->fetch_assoc()) {
?>
<article class="box">
    <!-- 每个商品套独立form表单,提交到当前页面 -->
    <form method="post" action="">
        <img src="<?= $row['image'] ?>" width="250px" height="300px">
        <h1> <?= $row['shoe_name'] ?></h1>

        <?php
        // 截断过长的商品描述
                $des = $row['shoe_description'];
                if (strlen($des)>70)
                {
                      // truncate string
                        $stringCut = substr($des, 0, 90);
                        $endPoint = strrpos($stringCut, ' ');
                        $des = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
                        $des .= '... <a class= "link" href="search.php">Read More</a>';
                }
        ?>
        <p> <?= $des ?> </p>
        
        <!-- 新增隐藏域存放当前商品的ID和名称,提交时会跟随POST请求传到后端 -->
        <input type="hidden" name="shoe_id" value="<?= $row['shoe_id'] ?>">
        <input type="hidden" name="shoe_name" value="<?= $row['shoe_name'] ?>">
        
        <input class="button" type="submit" name = "submit" value="Add to Cart" width= "150px"; />
    </form>
</article>
<?php } ?>
</section>
</main>

<?php
    require_once '../includes/footer.php';
?>
</html>

数组实现方案说明

如果你需要用数组形式实现,可以将所有商品放在同一个form内,给提交按钮的name设置为数组格式:

<input class="button" type="submit" name="submit[<?= $row['shoe_id'] ?>]" value="Add to Cart" width= "150px"; />

后端检测时读取$_POST['submit']的键名即可获取对应商品ID,该方案适合需要批量操作商品的场景,单商品添加购物车场景下独立表单方案更易维护。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 18:45:05