【问题标题】:What's wrong with the foreach loop in my php file?我的 php 文件中的 foreach 循环有什么问题?
【发布时间】:2018-04-16 03:47:19
【问题描述】:

下面是教授在课堂上复习的一些代码。我分了一部分,但没有做对。

这是 vardump 所说的:

注意:未定义变量:第 40 行 中的记录

警告:在第 40 行的 中为 foreach() 提供的参数无效

致命错误:未捕获的错误:在第 15 行的 中调用 boolean 上的成员函数 bind_param()

错误:在第 15 行的 中的布尔值上调用成员函数 bind_param()

我标记了第 40 行和第 15 行。

<?php
    $path = './';
    require $path.'../../../dbInfo.inc';
    if($mysqli){
        //IF we are adding a new user
        if( !empty($_GET['fName']) && !empty($_GET['lName'])){
            /*
                we are using client entered data - therefore we HAVE TO USE a prepared statement
                1)prepare my query
                2)bind
                3)execute
                4)close
            */
            $stmt=$mysqli->prepare("insert into 240Insert (last, first) values (?, ?)");
            $stmt->bind_param("ss",$_GET['lName'],$_GET['fName']); // LINE 15
            $stmt->execute();
            $stmt->close();
        }
        //get contents of table and send back...
        $res=$mysqli->query('select first, last from 240Insert');
        if($res){
            while($rowHolder = mysqli_fetch_array($res,MYSQLI_ASSOC)){
                $records[] = $rowHolder;
            }
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>DB Insert</title>
    </head>
    <body>
        <h3>The List</h3>
        <div id="list">
            <ul>
            <?php
                //var_dump($records);
                foreach($records as $this_row){ // LINE 40
                    echo '<li>' . $this_row['first'] . " " . $this_row['last'].'</li>';
                }
            ?>
            </ul>
        </div>
        <hr/>
        <h3>Add to the list</h3>
        <form action="dbInsertDone.php" method="get">
            First name: <input type="text" id="first" name="fName" />
            Last name: <input type="text" id="last" name="lName"/>
            <input type="submit" value="Add to the List"/>
        </form>
    </body>
</html>

编辑:为第 15 行添加错误

【问题讨论】:

  • 如果查询没有返回任何行,则永远不会创建 $records 数组。您应该在 SELECT 查询之前将其初始化为一个空数组。
  • 你应该定义 records = array();在 foreach 循环之外

标签: php mysqli foreach


【解决方案1】:

我查看了您的问题。您应该将循环外的$records 定义为array

$res=$mysqli->query('select first, last from 240Insert');
$records = array();
if($res){
    while($rowHolder = mysqli_fetch_array($res,MYSQLI_ASSOC)){
        $records[] = $rowHolder;
    }
}

希望这会有意义。

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 2017-10-02
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多