Php extract a set of values โ€‹โ€‹from a unique SQL string and display them in a list of HTML options

I am trying to display a SQL string that has a set of values โ€‹โ€‹in the HTML Select input.

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


| identifier | | Colors |


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


It must explode a set of values โ€‹โ€‹in the amount required!

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

      

How can I please do something like this:

"for the selected row id"
"select all color values โ€‹โ€‹and display each one in the 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...

+3


source to share


2 answers


What others have said is true, you are not doing it the best way in the database. However, if you must use a database like this, 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>';

      

+3


source


Try this: -



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

      

+2


source







All Articles