【问题标题】:Invalid argument supplied for foreach() when hitting the URL访问 URL 时为 foreach() 提供的参数无效
【发布时间】:2026-01-19 20:05:01
【问题描述】:

我现在有两个页面,分别称为 index.phpcheckout.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,是的,我忘了在问题中添加它。现在添加

标签: php html


【解决方案1】:

快速浏览您的代码,我认为您可以稍微修改一下

<?php

    session_start();
    /*
        `fruit` and `color` MUST be available
        before attempting to assign as any 
        sort of variable - so test here!
    */
    if( isset( 
            $_POST['submit'],
            $_POST['fruit'],
            $_POST['color']
        )){
        
        
        include('connection.php');
        /*
            It is not entirely clear why you would want to assign
            session values directly from POST values when you could
            simply work with the POST values instead.
        */
        $fruits=$_POST['fruit'];
        $colours=$_POST['color'];
        
        /*
            create the sql statement with placeholders
            which are then bound as parameters when the
            statement is executed.
            
            Create the statement once and assign new values
            inside of any loops rather than re-stating it
            on each iteration.
        */
        $sql='select `col1`, `col2`, ( select `democol` from `tbl_colors` where `c_id`=:cid ) as `democolor`
                from `tbl_mytable`
                where `id`=:id and `is_active`=1';
        
        $stmt=$pdo->prepare( $sql );

        
        
        /*
            Process the POSTed variables
            using the $key to access the values
            within the other array ( colours )
        */
        foreach( $fruits as $key => $value ) {
            try{
                if( isset( $colours[ $key ] ) ){
                    $stmt->execute( array(
                        ':cid'  =>  $value,
                        ':id'   =>  $colours[ $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();
            }
        }
    }
?>

仔细检查表明,您可能只有一个 SQL 查询来检索所有记录,方法是最初处理 POST 数据并生成包含各种 ID 的合适字符串,以便您在 sql 中使用 IN 运算符 - 例如如 where id IN (1,2,3) 等 - 比如:

$sql='select `col1`, `col2`, ( select `democol` from `tbl_colors` where `c_id` IN ( :cids ) ) as `democolor`
        from `tbl_mytable`
        where `id` IN ( :ids ) and `is_active`=1';
$stmt=$pdo->prepare( $sql );

$args=array(
    ':cids' =>  implode(',',array_values( $colours ) ),
    ':ids'  =>  implode(',',array_values( $fruits ) )
);

$stmt->execute( $args );

我希望这可能有用 - 我应该强调没有经过测试,所以可能会有错误,但希望不会。

【讨论】:

  • 给我一些时间来理解你的答案。
  • 是的,我用我的代码实现了你的答案,我需要了解 $stmt->execute( array( ':cid' => $value, ':id' => $colours[ $key ] ));
  • 我想我必须像这样使用 $stmt->execute(array( ':cid' => $colours[ $key ] , ':id' => $fruits[ $key ] ) );
  • 在 PDO 中,您可以通过几种方式将变量绑定到语句 - bindParambindValue 或通过将关联数组分配给 execute 方法,其键与 sql 语句中的占位符匹配.
  • 知道了,我测试了你的第一个解决方案,现在当我点击 URL 时,我变得空白。我不能使用第二种解决方案,因为我有两个表,并且我将 id 从一个表发送到第二个表以获取选定的行
最近更新 更多