How to get options in a form with values extracted from SQL database

25 views Asked by At
<select class="form-control" name="symbol">
    <option disabled selected value="">Symbol</option>
    <? for each($symbols as $symbols): ?>
    <option value="<?=$symbol?>"><?=$symbol?></option>
    <? endforeach ?>
</select>

$ symbols consists of data submitted by query (SELECT....) of cs50

1

There are 1 answers

1
Ultimater On

Almost, you were very close. It's: foreach($symbols as $symbol)

Also, it's a good idea to escape untrusted data before displaying it. For this purpose, I'd suggest htmlentities(...) The exception, of course, is if you were already storing it escaped in the database. I'd advise against this practice, though, as it's easy for the database to wind-up in an inconsistent state, especially over a long period of time, over many revisions.

So, altogether, that would be:

<select class="form-control" name="symbol">
   <option disabled selected value="">Symbol</option>
   <? foreach($symbols as $symbol): ?>
   <option value="<?=htmlentities($symbol)?>"><?=htmlentities($symbol)?></option>
   <? endforeach ?>
</select>