Mugs
Mugs

Reputation: 339

Why is this looping through each id in mysqli_fetch_assoc?

I don't understand why this provides a form option tab of each id in the array and not just one of them. Can someone explain? aka: Why is the $id variable not a static number. Thanks!

<form action="form_connect.php" method="post">

  <input type="text" name="username">
  <input type="password" name="password">
  <select name="id" id="">
  <?php
    while($row = mysqli_fetch_assoc($result)){
      $id = $row['id'];
      echo "<option value='$id'>$id</option>";
    }        
  ?>
  </select>
  <input type="submit" name="submit">

</form>

result that i'm confused by

Upvotes: 0

Views: 329

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

mysqli_fetch_assoc() returns an associative array, and considering you're calling it inside a while loop, you're iterating over each of the elements within that array. That is to say, apply the logic within the while loop to each of the elements in the array (individually, one at a time). Thus, each time you iterate over the array, the $id is set to the id value of the current element targeted by that iteration.

You then echo this out with echo "<option value='$id'>$id</option>", meaning that your <select> will be populated with multiple <option> elements, one for each element in the array.

Upvotes: 2

Related Questions