【发布时间】:2026-01-19 20:05:01
【问题描述】:
我现在有两个页面,分别称为 index.php 和 checkout.php。
在 index.php 页面中,我有 2 个复选框和 4 个单选按钮。
我正在做的是,当用户选中复选框和单选按钮并单击提交按钮时,我将复选框和单选按钮的值发送到 checkout.php 页面
并且该值将调用我的查询以在我的结帐页面上显示输出。
我尝试使用SESSION 将数据从一页发送到另一页,它正在工作。我在结帐页面上获得了POST 数据,并且我也在获得查询的输出。
现在我的问题是,如果我刷新页面,那么没有问题,但是当我点击 URL 时,我得到了错误
警告:为 foreach() 提供的参数无效 /home4/test/example/checkout.php 第 70 行
index.php
<form action="checkout.php" method="post" name="form1">
<div class="formWrapper">
<div class="form-group">
<fieldset>
<input type="checkbox" name="fruit[1]" value="1"><label>Fruit One</label><br />
<input type="radio" name="color[1]" value="1"><label>Black</label>
<input type="radio" name="color[1]" value="2"><label>Yellow</label>
</fieldset>
</div>
<div class="form-group">
<fieldset>
<input type="checkbox" name="fruit[2]" value="2"><label>Fruit Two</label><br />
<input type="radio" name="color[2]" value="1"><label>Black</label>
<input type="radio" name="color[2]" value="2"><label>Yellow</label>
</fieldset>
</div>
<input type="submit" name="submit" value="Next">
</div>
</form>
checkout.php
<?php
session_start();
include('connection.php');
if(isset($_POST['submit'])){
$_SESSION['fruits']=$_POST['fruit'];
$_SESSION['colors']=$_POST['color'];
foreach ($_SESSION['fruits'] as $key => $value) {
try{
$sqlquery="SELECT col1,col2, (select demoCol from tbl_colors where c_id=:c_id) as demoColor FROM tbl_mytable WHERE id=:id and is_active=1";
$stmt = $pdo->prepare($sqlquery);
$stmt->execute( array(':c_id' => $_SESSION['colors'][$key],':id'=>$_SESSION['fruits'][$key]) );
$result = $stmt->fetchAll();
foreach ($result as $row) {?>
<h3><?php echo $row['col1'];?> <?php echo $row['col2'];?></h3>
<p><?php echo $row['demoColor'];?></p>
<?php
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
}
?>
【问题讨论】:
-
第 70 行是哪一行?
foreach ($_SESSION['fruits']或foreach ($result as?? -
您的查询逻辑也有点偏差。在循环之前创建一次
prepared statement,并在循环中使用不同的值进行调用。但这就是说您将变量直接嵌入到 sql 本身中,这违背了准备语句的目的 -
@ProfessorAbronsius,我遇到了这个问题 $stmt = $pdo->prepare($sqlquery);这是在尝试块
-
你知道花括号也少了吗?
-
@ProfessorAbronsius,是的,我忘了在问题中添加它。现在添加