PHP - 从数据库中获取值并设置为HTML select标记的值

PHP  - 从数据库中获取值并设置为HTML select标记的值

问题描述:

Hope someone can help me out. Developing a stock management system for a herb factory in PHP with a MySQL database. I'm currently developing a page where the user can edit the value of one of the benches that holds the herbs.

I've drawn in the benches details and they're in an array called $bench_data which contains variable herb, quantity, etc.

I have a html select tag where the user selects the herb being produced

Herb*:<br>
<select name='herb' ">
   <option value="default">-----</option>
   <option value="basil">Basil</option>
   <option value="coriander">Coriander</option>
   <option value="parsley">Parsley</option>
   <option value="mint">Mint</option>
   <option value="rosemary">Rosemary</option>
   <option value="thyme">Thyme</option>
</select>

What I want to do is have the herb value of the selected bench already in the select tag when the user enters the page.

I've managed to do it with quantity - 'the php in value'

Quanity<br>
<input type="text" name="quantity" value="<?php echo $bench_data['quantity']; ?>">

but I don't know how to do it when there are different options

Thanks in advance

You use the "selected" attribute to tell the browser which option should be showing on page load. For example, on each option do it like this:

<option value="basil" <?php if ($bench_data['herb']=='basil'){echo 'selected';}?>>
Basil
</option>

Here's a helpful link