我有这组代码,允许我的表单保留存储在表字段中的值。
<?php
$playerpositions = Array("Coach", "Assistant Coach", "Goalkeeper", "Defense", "Midfield", "Forward");
?>
<select name="playerposition" id="playerposition" class="input-field-login2" tabindex="1">
<option value="-1">Select to Change</option>
<?php
foreach($playerpositions as $v) {
$selected = ($row_player['plyPosition']===$v) ? "selected" : "";
echo "<option value='$v' $selected>$v</option>";
}
?>
</select>
我现在的问题是,可以有一个阵列
$playerpositions = Array("Coach", "Assistant Coach", "Goalkeeper", "Defense", "Midfield", "Forward");
如下所示是动态的
$playerpositions = Array(while ($row_playersa = mysqli_fetch_assoc($result_playersa)) {
$playersa[] = $row_playersa;
});
这可能吗?因为我想要做的不是将数组项硬编码,我希望它们从表中拉出来。还是有另一种方法可以做到这一点吗?
答案 0 :(得分:0)
对这些类型的东西进行硬编码通常是最后的选择。如果您需要在其他地方实现相同的下拉菜单,该怎么办?从数据库表中存储和检索是有意义的,因为您可以在一个地方修改类型并在其他地方引用它们,而无需在许多地方复制,粘贴和维护相同的代码。
但是,你不能像这样构建一个数组。你会这样做的方式是:
// example code, not real, assume it produces
// array("Coach", "Assistant Coach", "Goalkeeper", "Defense", "Midfield", "Forward");
$someQuery = "SELECT * FROM `player_positions`";
$playerPositions = $db->execute($someQuery);
// other code...
// Iterate through your playerPositions and produce your options.
foreach ($playerPositions as $v) {
echo "<option value='$v' $selected>$v</option>";
}
答案 1 :(得分:0)
是
$playerposition = array();
while ($row_playersa = mysqli_fetch_assoc()) {
$playerposition [] = $row_playersa['name'];
}
foreach($playerposition as $position){
$selected = ($player_row[$plyPosition]===$position) ? "selected" : null;
echo '<option value="'. $position .'" ' . $selected . '>'. $position .'</option>';
}