使用相同的值填充多个选择选项。
在这个问题上扩大一点:Populating dropdown with query results in PHP
如果我要使用同一SQL查询填充多个选择项,是否可以循环遍历整个表以将其全部填充?
我有这个:
<td class="tg-0pky"><Select length ="10" name ="30DayEmail" value="'.$row['30DayEmail'].'">';
$sql = "SELECT Health FROM health LIMIT 3";
$Health_results = mysqli_query($link, $sql);
while($Health_row = mysqli_fetch_assoc($Health_results)) {
echo "\t\t".'<option value="'.$Health_row['Health'].'">'.$Health_row['Health'].'</option>'."\n";
}
那很好,但是我不想将其粘贴到我拥有的其他50个选择选项中。
答案 0 :(得分:0)
您可以改为将SQL查询中的所有结果检索到一个数组中(使用mysqli_fetch_all()
),然后每次针对每次选择都遍历结果数组...
$sql = "SELECT Health FROM health LIMIT 3";
$Health_results = mysqli_query($link, $sql);
$health_values = mysqli_fetch_all($Health_results, MYSQLI_ASSOC);
foreach ( $health_values as $health) {
echo "\t\t".'<option value="'.$health['Health'].'">'.$health['Health'].'</option>'."\n";
}
或者,如果每个选项列表完全相同,则可以在开始时构建一个字符串,然后每次都回显此字符串...
$sql = "SELECT Health FROM health LIMIT 3";
$options = '';
$Health_results = mysqli_query($link, $sql);
while($Health_row = mysqli_fetch_assoc($Health_results)) {
$options.= "\t\t".'<option value="'.$Health_row['Health'].'">'.$Health_row['Health'].'</option>'."\n";
}
然后可以每次使用$options
。
答案 1 :(得分:0)
将结果放入变量中,以便您可以在所有位置回显它。
$options = "";
$sql = "SELECT Health FROM health LIMIT 3";
$Health_results = mysqli_query($link, $sql);
while($Health_row = mysqli_fetch_assoc($Health_results)) {
$options .= "\t\t".'<option value="'.$Health_row['Health'].'">'.$Health_row['Health'].'</option>'."\n";
}
echo '<td class="tg-0pky"><Select length ="10" name ="30DayEmail" value="'.$row['30DayEmail'].'">'.$options.'</select></td>';