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

HTML按钮提交表单无法获取对应行正确customer_id值求助

错误原因
  • 所有行的customer_id隐藏输入框都放在同一个<form>标签内,同名的表单参数提交时会被后面的定义覆盖,因此后台永远只能拿到最后一行的customer_id
  • 存在HTML标签嵌套错误:循环内每次输出<tr>,但循环外只执行一次</tr>闭合,会导致表格结构错乱
修正方案

方案1:每行单独绑定form(最简便,无需修改后端代码)

前端渲染代码修改为如下:

<table>
   <thead>
      <tr>
         <th>First Name</th> <th>Last Name</th> <th>Customer ID</th><th>Info</th>
      </tr>
   </thead>
   <tbody>
         <?php 
         $sql = "select fname, lname,customer_id from customer_address ";
         $result = mysqli_query($conn,$sql);
         while($row = mysqli_fetch_assoc($result)){
            $fname = $row['fname'];
            $lname = $row['lname'];
            $customer_id = $row['customer_id'];
            echo "<tr>";
            echo "<td>$fname</td>";
            echo "<td>$lname</td>";
            echo "<td>$customer_id</td>";
            echo "<td>
              <form method='post'>
                <input type='hidden' name='customer_id' value='$customer_id'>
                <button type='submit' name='submit'>More Info</button>
              </form>
            </td>";
            echo "</tr>";
          }
         ?>
   </tbody>
</table>

后端接收代码无需修改即可正常获取对应行的customer_id。

方案2:使用button的value属性传递参数(无需隐藏输入框)

前端代码修改为:

<form method="post">
<table>
   <thead>
      <tr>
         <th>First Name</th> <th>Last Name</th> <th>Customer ID</th><th>Info</th>
      </tr>
   </thead>
   <tbody>
         <?php 
         $sql = "select fname, lname,customer_id from customer_address ";
         $result = mysqli_query($conn,$sql);
         while($row = mysqli_fetch_assoc($result)){
            $fname = $row['fname'];
            $lname = $row['lname'];
            $customer_id = $row['customer_id'];
            echo "<tr>";
            echo "<td>$fname</td>";
            echo "<td>$lname</td>";
            echo "<td>$customer_id</td>";
            echo "<td><button type='submit' name='customer_id' value='$customer_id'>More Info</button></td>";
            echo "</tr>";
          }
         ?>
   </tbody>
</table>
</form>

对应后端代码修改为:

<?php
$ccf=" ";
if(isset($_POST['customer_id'])){
  $ccf = $_POST['customer_id'];
}
echo "Customer Id selected is:$ccf";
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:27:02