简体   繁体   中英

What's wrong with the foreach loop in my php file?

So here's some code that the professor went over in class. I zoned out for a portion and I didn't get something right.

Here's what the vardump said:

Notice: Undefined variable: records in < file location > on line 40

Warning: Invalid argument supplied for foreach() in < file location > on line 40

Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in < file location> on line 15

Error: Call to a member function bind_param() on boolean in < file location > on line 15

I have line 40 and 15 labeled.

<?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>

EDIT: Added errors for line 15

I reviewed your question. You should define $records outside the loop as an array .

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

Hope this will make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM