如何将以下选择字段默认为当前选定的rid?
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name='rid'>
<?php
$query= "SELECT * FROM resources ORDER BY resname";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$rid = $row['rid'];
echo "<option value='".$rid."'>"
.$row['resname']
."</option>\n";
}
?>
</select>
<input type=submit>
</form>
这些代码非常丑陋,不要吝啬我。
答案 0 :(得分:1)
我强烈建议您查看PDO或MYSQLi,因为从PHP 5.5.0开始,mysql_
已弃用。
无论如何,我们可以使用ternary operator
快速完成echo "<option value='".$rid."' ".((isset($_GET['rid']) && $_GET['rid'] == $rid) ? 'SELECTED' : '').">"
答案 1 :(得分:1)
$query = "SELECT * FROM resources ORDER BY resname";
$result = mysqli_query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['rid'] . "'";
if (isset($_POST['rid']) && $_POST['rid'] == $row['rid']) {
echo ' selected="selected"';
}
echo ">" . $row['resname'] . "</option>";
}
答案 2 :(得分:0)
$query = "SELECT * FROM resources ORDER BY resname";
$result = mysqli_query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['rid'] . "'";
if (isset($_GET['rid']) && $_GET['rid'] == $row['rid']) {
echo ' selected="selected"';
}
echo ">" . $row['resname'] . "</option>\n";
}