我有一个非常简单的形式,我希望用户选择是升序还是降序。从选择表单中,我将使用答案按要求的顺序提供搜索结果。我的问题是表单没有给页面提供结果,并且两个'if'语句都满足。我完全难过了。谁能摆脱光明?谢谢
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="sort">Sort by:</label>
<select name="thesort">
<option value="Lowest">Lowest first</option>
<option value="Highest">Highest first</option>
</select>
</form>
<?php
if(isset($_POST["thesort"])){
echo "selection has been made";
}
?>
<?php if($_POST["thesort"]=="Highest"){ echo 'selected="selected"';}
{
echo "<p> choice is DESC </p>";
}
?>
<?php if($_POST["thesort"]=="Lowest"){ echo 'selected="selected"';}
{
echo "<p> choice is ASC </p>";
?>
答案 0 :(得分:2)
为什么要双花括号? PHP将在任何情况下执行第二个。
if($_POST["thesort"]=="Highest")
{ echo 'selected="selected"';}
{echo "<p> choice is DESC </p>";}
您的代码已修改:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="sort">Sort by:</label>
<select name="thesort">
<option value="Lowest">Lowest first</option>
<option value="Highest">Highest first</option>
</select>
</form>
<?php
if(isset($_POST["thesort"])){
echo "selection has been made";
}
if($_POST["thesort"]=="Highest"){
echo 'selected="selected"';
echo "<p> choice is DESC </p>";
}
if($_POST["thesort"]=="Lowest"){
echo 'selected="selected"';
echo "<p> choice is ASC </p>";
}
?>
答案 1 :(得分:0)
这是一个问题:
<?php if($_POST["thesort"]=="Highest"){ echo 'selected="selected"';}
{
echo "<p> choice is DESC </p>";
}
?>
a)那些括号不符合我认为你认为他们正在做的事情。特别是,第二组是无关紧要的;该代码将始终执行
b)为什么你在这里回应'选择= ..'?它不在开放<option
标记的上下文中。例如,您可能需要以下内容:
echo '<option value="Highest';
if ($_POST["thesort"]=="Highest")
{
echo ' selected="selected"';
}
echo '">Highest first</option>';
答案 2 :(得分:0)
<?php
$sort = 'Lowest'; // define the default
if (isset($_POST['thesort']) && $_POST['thesort'] == 'Highest') {
$sort = 'Highest';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="sort">Sort by:</label>
<select name="thesort">
<option value="Lowest"<?php if ($sort == 'Lowest') print(' selected="selected"'); ?>>Lowest first</option>
<option value="Highest"<?php if ($sort == 'Highest') print(' selected="selected"'); ?>>Highest first</option>
</select>
</form>