这是我的代码
<?php
$count = 1;
$sql = "SELECT * FROM `scheduledata`
WHERE `departdate` = '$departdatephp'
AND `orginplace_id` = '$orginplacephp'
AND `desplace_id` = '$desplacephp' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<th><?php echo $count;?></th>
<th><?php echo $row["departtime"];?><input type="hidden" name="departtime" value="<?php echo $row['departtime'];?>" method="post"></th>
<th><?php echo $row["returntime"];?><input type="hidden" name="returntime" value="<?php echo $row['returntime'];?>" method="post"></th>
<th><?php echo $row["adultprice"]; ?>MYR<input type="hidden" name="adultprice" value="<?php echo $row['adultprice'];?>" method="post"></th>
<th><?php echo $row['schedule_id'];?><input type="hidden" name="scheduleid" value="<?php echo $row['schedule_id'];?>" method="post"></th>
<th><?php echo $row['flight_id'];?><input type="hidden" name="flightid" value="<?php echo $row['flight_id'];?>" method="post"></th>
<th><button type="submit" class="submit-button" method="post" name="departbtn[]">booking</button></th>
<?php
$count = $count+1;}
?>
</tr>
Lest说我有3种这样的预订选择 3 booking button
这是我的输出代码
<?php
if(isset($_POST['departbtn']))
{
$departtimephp = $_POST['departtime'];
$returntimephp = $_POST['returntime'];
$price = $_POST['adultprice'];
$scheduleid = $_POST['scheduleid'];
$flightid = $_POST['flightid'];
$_SESSION['departtime'] = $departtimephp ;
$_SESSION['returntime'] = $returntimephp ;
$_SESSION['adultprice'] = $price ;
$_SESSION['scheduleid'] = $scheduleid ;
$_SESSION['flightid']= $flightid ;
print_r($_SESSION['departtime']);
print_r($_SESSION['returntime']);
print_r($_SESSION['adultprice']);
print_r($_SESSION['scheduleid']);
print_r($_SESSION['flightid']);
}
?>
无论我选择哪个选项,输出总是表的最后一行,我猜这是因为所有变量都有相同的名称,所以系统直接插入最后一行数据。 我的问题有点像 here ,他们建议使用 array[] 来解决这个问题,但是当我在 isset 中添加 foreach 时出现错误,所以知道如何获取正确的数据吗? 感谢任何解决方案。
最佳答案
显示的代码没有明确显示这一点,但我强烈怀疑整个表格就是您的表单
。这意味着无论您单击哪个按钮,所有值都会被提交。
对于初学者来说,浏览器不会知道您“指的是”哪一个,并且任何给定值都会覆盖 POST 表单中的前一个值。 (这解释了你所看到的行为......你总是得到最后一条记录。)但是,除此之外......为什么?当您实际上只需要所选记录的单个标识符时,为什么要提交所有数据?
对于表中的每一行,放置一个完整的独立表单
。像这样的事情:
<tr>
<!--- your other table cells --->
<th>
<form method="post" action="someAction.php">
<input type="hidden" name="flightid" value="<?php echo $row['flight_id'];?>" />
<button type="submit" class="submit-button" method="post" name="departbtn">booking</button>
</form>
</th>
</tr>
(您可以在那里放置更多的隐藏
表单字段,只要您愿意就可以。不过说实话,您应该只需要一个标识符。服务器已经拥有其余的数据。并且您使用的字段越多,用户就有更多机会干扰系统。)
这样,当您单击按钮时,所选择的选项就不会含糊不清。每个表单都是完全独立的,只有需要发布的数据。
关于php - 只能将表的最后一行数据插入到 session 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38686959/