简体   繁体   English

在PHP中使用foreach循环显示具有两个值的php mysql结果

[英]Displaying a php mysql result with two values with a foreach loop in PHP

I have result that I want to display as a drop down menu. 我有想要显示为下拉菜单的结果。 The query selects id and name from a table. 该查询从表中选择ID和名称。

        $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. 如果我只想显示name作为值和显示给用户,这将很好用。 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. 但是我要做的是将所选ID用作选择选项的“值”,并且我想向用户显示所选名称。 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. 提前致谢。

mysqli_fetch_array() is a function which converts your query results into an array. mysqli_fetch_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>

No need for the foreach iteration; 无需foreach迭代; mysqli_fetch_array() already provides an associative array. mysqli_fetch_array()已经提供了一个关联数组。 After each fetch do 每次抓取后

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

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: foreach是不必要的-在mysqli_fetch_array命令上使用while循环将返回数组每一行的所有结果-您可以像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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