PHP form results to same page
I have a very simle form, i wish the user to choose whether to sort ascending or decending. From the select开发者_运维问答 form, I will use the answer to give the search results in required order. My problem is that the form is not giving a result to the page and both 'if' statements are satisfied. I am completely stumped. Can any one shed light? Thank you
<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>";
?>
Why double curly braces? PHP will execute the second one in ever case.
if($_POST["thesort"]=="Highest")
{ echo 'selected="selected"';}
{echo "<p> choice is DESC </p>";}
Your code modified:
<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>";
}
?>
This is a problem:
<?php if($_POST["thesort"]=="Highest"){ echo 'selected="selected"';}
{
echo "<p> choice is DESC </p>";
}
?>
a) Those brackets aren't doing what I think you think they're doing. In particular, the second set are irrelevant; that code will always execute
b) Why are you echo'ing 'selected=..' here? It's not in the context of an open <option
tag. For example, you probably want something like:
echo '<option value="Highest';
if ($_POST["thesort"]=="Highest")
{
echo ' selected="selected"';
}
echo '">Highest first</option>';
<?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>
精彩评论