0

I have result that I want to display as a drop down menu. The query selects id and name from a table.

        $usersQuery = "SELECT id, name
        FROM users";
        $usersResult = mysqli_query ($dbc, $usersQuery);

I want to use this result as a list in a drop down menu. This is what i have so far.

      <select id="dropdown" name="dropdown">
        <option value="select" selected="selected">Select</option>
       <?php
        while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
          foreach ($usersRow as $value){
            echo "<option value=\"$value\"";
            echo ">$value</option>\n";
          }
        }
        ?>
      </select>

this would work fine if I just wanted to display name as both the value and the display to the user. But what I want to do is use the selected id as "value" for the select option and I want to show the name selected to the user. I have tried this but it does not work.

  <select id="dropdown" name="dropdown">
    <option value="select" selected="selected">Select</option>
   <?php
    while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
      foreach ($usersRow as $id=>$name){
        echo "<option value=\"$id\"";
        echo ">$name</option>\n";
      }
    }
    ?>
  </select>

Any help would be great.

Thanks in advance.

1
  • 1
    try to ask clear and as-short-as-possible question which go to the very core of the problem... php, mysql, foreach, ... that doesn't look like real problem. Commented Jan 26, 2012 at 12:42

3 Answers 3

5

mysqli_fetch_array() is a function which converts your query results into an array. which means you can display your values like you would with a normal array value.

<select id="dropdown" name="dropdown">
    <option value="select" selected="selected">Select</option>
   <?php
    while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){


        echo "<option value=\"".$usersRow['id']."\"";
        echo ">".$usersRow['name']."</option>\n";

    }
    ?>
  </select>
Sign up to request clarification or add additional context in comments.

Comments

1

No need for the foreach iteration; mysqli_fetch_array() already provides an associative array. After each fetch do

// Assuming "id" is a numeric value
printf('<option value="%d">%s</option>', $usersRow['id'], $usersRow['name']);

1 Comment

It should be noted that when only associative keys are required, it is (slightly) more efficient to use mysqli_fetch_assoc()
0

The foreach is unnecessary - using a while loop on the mysqli_fetch_array command will return all the results with each row in an array - you can use it like so:

while ($usersRow = mysqli_fetch_array($usersResult, MYSQLI_ASSOC)){
    echo "<option value=\"".$usersRow['id']."\"";
    echo ">".$usersRow['name']."</option>\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.