This code works.
<!doctype html>
<body>
<form method="post" >
<?php
$conn = new mysqli('localhost', 'root', '', 'myDB');
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql='SELECT DISTINCT counselor_name FROM counselors';
$result = $conn->query($sql);
?>
<select name="name" >
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['counselor_name'].'">'.$row['counselor_name'] . '</option>';
}
?>
</select>
<input type="submit" value="GO!" name="go"/>
</form>
</body>
对于我的生活,我无法弄清楚如何将select函数合并到选项字符串中以选择值。 IE:如果我要设置$ filter =&#34; John&#34;。我想&#34; John&#34;被选中。
提前致谢
答案 0 :(得分:0)
您可以使用三元运算符在一行(现有的回显线)中进行,但为了便于阅读,这就是您想要的:
if ($row['counselor_name'] === $filter)
{
echo '<option value="'.$row['counselor_name'].'" selected="selected">'.$row['counselor_name'] . '</option>';
}
else
{
echo '<option value="'.$row['counselor_name'].'">'.$row['counselor_name'] . '</option>';
}