【问题标题】:PHP form results to same pagePHP表单结果到同一页面
【发布时间】:2011-11-10 04:39:37
【问题描述】:

我有一个非常简单的表格,我希望用户选择是升序还是降序。从选择表单中,我将使用答案按要求的顺序给出搜索结果。我的问题是表单没有为页面提供结果,并且两个“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>";


 ?>

【问题讨论】:

  • 您是否启用了错误报告?还可以尝试简化问题,通过简化逻辑直到获得预期的输出,然后逐段添加代码。
  • 不要使用 POST 进行排序。请改用 GET。

标签: php forms select post


【解决方案1】:
<?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> 

【讨论】:

  • 为什么你们都使用 POST 进行排序?
  • @Col。 Shrapnel:因为这可能是 OP 的问题?
【解决方案2】:

这是个问题:

<?php if($_POST["thesort"]=="Highest"){ echo 'selected="selected"';} 
{
    echo "<p> choice is DESC </p>";
}
?>

a) 那些括号没有做我认为你认为他们正在做的事情。特别是,第二组无关紧要;该代码将始终执行

b) 你为什么在这里回显“selected=..”?它不在打开的&lt;option 标签的上下文中。例如,您可能想要这样的东西:

echo '<option value="Highest';

if ($_POST["thesort"]=="Highest")
{
    echo ' selected="selected"';
}

echo '">Highest first</option>';

【讨论】:

    【解决方案3】:

    为什么要用双花括号? 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>";
    }
    ?>
    

    【讨论】:

    • echo 'selected="selected"'; 可能放错了位置,但这不是这个答案的领域。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2011-08-06
    • 1970-01-01
    • 2014-03-10
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多