Question

I'm trying to create a select box full of options based on data from an array that is built from an sql query, I've tried researching where I'm going wrong but the closest I've managed to get is echoing alot of empty option boxes my code is as follows:

$result = mysqli_query($cons,"SELECT user_name FROM users");
while($row = mysqli_fetch_array($result)){
foreach($row as $key => $value){
echo '<option value="'.$value.'"</option>';}}

If anybody could point me in the right direction that would be great.

EDIT: I can't believe it was something as simple as that! Thank you very much.

On a separate note It's actually giving all of the data twice.

I'll mark as correct answer as soon as I can.

Was it helpful?

Solution

echo '<option value="'.$value.'">'.$value.'</option>';

or

echo "<option value=\"{$value}\">{$value}</option>";

You never closed the opening option tag. If you view your source you'll see it's wonky.

BTW, You don't need the value="" part if you're using the same value in the text of the option.

echo "<option>{$value}</option>";

Entire code as I would do it

$result = mysqli_query($cons,"SELECT user_id, user_name FROM users");
while($row = mysqli_fetch_assoc($result)){
    echo "<option value=\"{$row['user_id']}\">{$row['user_name']}</option>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top