【问题标题】:php if statement from html option value error来自html选项值错误的php if语句
【发布时间】:2018-03-06 05:35:50
【问题描述】:

我正在尝试复制以下内容:

php if statement html option value 并按照建议的指示进行操作:

为您的选择命名。

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

在php中

Example:

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.
}

但是,我收到以下错误:

注意:未定义索引:第 7 行 C:\xampp\trial.php 中的 selectedValue

请帮忙

【问题讨论】:

  • 请确认是否选择了任何选项。
  • 一加载页面就会出现错误,即使我选择了一个选项,也没有任何变化。
  • $_POST 仅在您提交表单时填写。当您第一次加载页面时,它不会有任何值。在尝试使用参数之前,您需要检查表单是否已提交。
  • 怎么样?我应该添加提交按钮吗?

标签: php html forms


【解决方案1】:

如果您要发送表单数据,那么您必须在表单标签中设置方法 post,或者如果您使用 ajax 通过类型 post 发送它,并且在您的 php 文件中将代码放入 if 条件后的表单已发布,如 isset($ _POST['selectedValue'])

<form method="post" action="url to your php file">
   <select name="selectedValue">
      <option value="Newest">Newest</option>
      <option value="Best Sellers">Best Sellers</option>
      <option value="Alphabetical">Alphabetical</option>
   </select>
   <button type="submit">Submit</button>
</form>

【讨论】:

    【解决方案2】:

    这是因为您的 selectedValue 数组中并不总是有键 selectedValue

    if(isset($_POST['selectedValue'])){
       // your code
    }
    

    【讨论】:

      【解决方案3】:

      在 HTML 的表单标签中添加提交按钮后,我的问题解决了

      <form  action="#" method="post">
          <select name="selectedValue">
              <option value="Newest">Newest</option>
              <option value="Best Sellers">Best Sellers</option>
              <option value="Alphabetical">Alphabetical</option
          </select>
          <input type="submit" style="float:left; margin-left: 2%;" name="submit" value="Search"/>
      </form>
      

      【讨论】:

        猜你喜欢
        • 2013-02-27
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        • 2017-05-07
        • 2016-07-21
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        相关资源
        最近更新 更多