PHP if语句的HTML选项值


php if statement html option value

假设您有以下html select语句

<select>
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>

现在我要运行一个php if elseif语句

if (option value = newest) {
// Run this
}
elseif ( option value = best sellers ) {
// Run this
}

等。但我不知道在if else语句里放什么。换句话说,而不是'option value = latest '(我知道是不正确的),我可以把什么放在那里,以便如果选择了latest,它将执行if语句,或者如果选择了bestsellers,它将执行elseif语句?

给你选择的名字

<select name="selectedValue">
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>

在你的PHP中,你会这样做:

$_POST['selectedValue'];

如果我是你,我更喜欢切换大小写在这种情况下,有两个以上的条件。

的例子:

switch($_POST['selectedValue']){
case 'Newest':
    // do Something for Newest
break;
case 'Best Sellers':
    // do Something for Best seller
break;
case 'Alphabetical':
    // do Something for Alphabetical
break;
default:
    // Something went wrong or form has been tampered.
}

首先给select添加一个名称:

<select name="demo">
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>
然后

if ($_POST['demo'] === 'Newest') {
// Run this
}
elseif ( $_POST['demo'] === 'Best Sellers' ) {
// Run this
}

switch($_POST['demo']){
    case 'Newest' : 
        //some code;
        break;
    case 'Best Sellers':
        //some code;
        break;
    default:
        //some code if the post doesn't match anything
}

<select>应具有name属性,例如<select name="sortorder">。然后可以说

if ($_REQUEST['sortorder'] == 'Newest') {
  // TODO sortorder 'Newest' was selected.
}

如果您知道表单数据是通过HTTP GET还是HTTP POST进入的,您可以分别使用$_GET['sortorder']$_POST['sortorder']

我认为阅读友好的版本应该是:

switch($option){
    case 'Newest':
        runNewestFunction();
    break;
    case 'Best Sellers':
        runBestSellersFunction();
    break;
    case 'Alphabetical':
        runAlphabeticalFunction();
    break;
    default:
        runValidationRequest();
}

还请添加名称属性<select name="option">