Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php retrieve a set of values from an unique SQL row and display it in an HTML option list

Tags:

sql

php

select

I am trying to display an SQL row which has a set of values in an HTML Select input.

Here is my table (row color is a varchar type) :


|id| |colors|


|12| Red, Green, Blue
|13| Yellow, Green |14| Yellow


It should implode the set of values in as many as needed!

<select>
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>

How can I do, please, something like this :

"for a selected row id"
"fetch all the color values and display each of them in an value"

echo '<select>';
$results = mysql_query("SELECT colors FROM MyTable where id='$id'");
while($rows = mysql_fetch_assoc($results)) {
echo '<option>'.implode($rows['colors']).'</option>';
}
echo '</select>';

Thank you...

like image 614
bat .t Avatar asked Dec 05 '25 22:12

bat .t


1 Answers

What the others have said is correct, you are not doing it the best way in the database. However, if you are required to use such a database, this code should help:

echo '<select>';
$results = mysql_query("SELECT colors FROM MyTable where id='$id'");
while($row = mysql_fetch_assoc($results))
    $colors = explode(",", $row['colors']);
    $arr_length = count($colors);
    for ($i=0; $i<$arr_length; $i++){
        echo '<option>'.$colors[$i].'</option>';
    }

}
echo '</select>';
like image 99
kojow7 Avatar answered Dec 08 '25 10:12

kojow7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!