0

I'm trying to make a form being generated by using for and foreach loops. Idea is simple but for some reason i'm having odd issue. For loop is supposed to have 5 iterations and this is working fine but in this for loop i have embedded a foreach loop. Foreach loop seems to be done only on first iteration of for loop. I think code is ok but maybe multiple concatenations obscure my vision to find where my mistake is. This is how the code looks at the moment:

<?php
include("pdo.php");

$stmt = $pdo->query('SELECT name FROM Ingredients');
?>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <form>
            <?php
            for ($i = 1; $i <= 5; $i++) {
                echo "<label>Ingredient $i</label><select name='ingredient $i'>";
                foreach ($stmt as $row) {
                    echo ('<option value="' . $row['name'] . '">' . $row['name'] . '</option>' . "\n");
                }
                echo "</select><br>";
            }
            ?>
        </form>
    </body>
</html>

In other words only first list is being populated but next four lists are empty.

spectatorx
  • 373
  • 2
  • 7
  • 22

1 Answers1

2

Once you have read all rows returned in the statement you can't read them again, you would need to rewind the result before populating each select. Instead use fetchAll to get result as an array.

dhinchliff
  • 1,106
  • 8
  • 17