我正在做一本食谱书,下一步是为该食谱添加成分,为此,我使用形式:
<form id="" method="POST" action="add_ingredients.php" enctype="multipart/form-data">
<label for="ingredient" class="required">Name</label>
<input type="text" name="ingredient" />
<div>
<input name="attach_id" type="text" value="" class="hidden" />
<label for="description" class="required">Description:</label>
<textarea name="description"></textarea>
<div>
<?php $units = get_units();
?>
<label for="units" class="required">Units</label>
<select name="units">
<option value="" disabled selected>Select a unit</option>
<?php
foreach ($units as $unit) {
echo '<option value="' . $unit['id'] . '"';
if (isset($unit['id'])) {
echo ' selected';
}
echo '>' . $unit['name'] . '</option>';
}
?>
</select>
</div>
<label for="file">Image</label>
<input type="file" name="photo" id="photo"><br>
</div>
<button class="submit" type="submit" name="submit">Submit</button>
</form>
但问题是,选择下拉列表中的选定选项不会获取select属性,或者在这种情况下(使用if(isset$unit['id'])
)所有选项都会获得选定的属性。
如何使用下拉列表选择我实际选择的选项?
get_units
功能从表单位:
function get_units() {
include 'db_connection.php';
$sql = 'SELECT * FROM units';
try {
$results = $conn->prepare($sql);
$results->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return $results->fetchAll(PDO::FETCH_ASSOC);
}
谢谢