PHP Drop Down Data from Database

2019-03-04 02:03发布

问题:

I am trying to make an select field for data according to my database. So, basically, I want it to have a dropdown menu for all the users in my database. So like instead of doing:

<select>
  <option>1st User in Db</option>
  <option>2nd User in Db</option>
</select>

It just automatically shows all.

I tried fetching a $row['uname'], and setting it as $user, but then it only shows MY user in the dropdown.

Example: http://prntscr.com/dwksy

It only shows my account, admin, instead of all the other ones. Anyone know how to do this? Thanks!

回答1:

<?php

session_start();
include 'config.php';
$user = $_SESSION['username'];
$qry=("SELECT `rank`, `uname` FROM users WHERE uname='$user'");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row["rank"]

if ($_SESSION['loggedin'] == true) {
    if ($rank >= 3) {
        $qry=("SELECT `rank`, `uname` FROM users");
        $result=mysql_query($qry);

        echo "
        <form action='' method='POST'>
        <select>";

        while ($row = mysql_fetch_assoc($result)) {
            $rank = $row['rank'];
            $users = $row['uname'];
            $lol = ucwords($users);

            echo "<option>$lol</option>";
        }

        echo "</select>
        </form>
        ";
      } else {
          echo "Your level is not 3, but you are logged in.";
      }
  } else {
     echo "Please login.";
  }


回答2:

Your query only fetches the user recorded in $_SESSION. Drop the WHERE clause to get all users in the result, then read them with @andrewsi's loop and spit out one <option> for each user returned:

$qry=("SELECT `rank`, `uname` FROM users");