尝试从PHP中选择一个来自多个答案

时间:2018-05-25 11:32:04

标签: php

以下代码是我试图通过单击提交按钮进行多项选择的文件中的HTML:

<form id="eg6b" action="example-6.php" method="post">
     <p>
    <label for="sport">Favourite sport: </label>
    <select id="sport" name="favsport []" size="4" multiple>
        <option value="soccer">Soccer</option>
        <option value="cricket">Cricket</option>
        <option value="squash">Squash</option>
        <option value="golf">Golf</option>
        <option value="tennis">Tennis</option>
        <option value="basketball">Basketball</option>
        <option value="baseball">Baseball</option>
    </select>


     <input type="submit" value="submit"></p>
 </form>

以下代码是获取多个Sports的PHP文件:

<?php

      foreach($_POST["favsport"] as $val) {
         echo "<p>You chose $val </p>";
      }

  ?>

我无法找到错误。如果我运行此代码,则会给出the favsport is undefined and that the argument supplied to the foreach loop is invalid错误。我已经搞砸了很多,但现在我只是累了。

2 个答案:

答案 0 :(得分:1)

favsport []更改为favsport[]

 <!DOCTYPE html>
      <html>
      <head>
        <title></title>
      </head>
      <body>
    <form id="eg6b" action="test.php" method="post">
         <p>
        <label for="sport">Favourite sport: </label>
        <select id="sport" name="favsport[]" size="4" multiple>
            <option value="soccer">Soccer</option>
            <option value="cricket">Cricket</option>
            <option value="squash">Squash</option>
            <option value="golf">Golf</option>
            <option value="tennis">Tennis</option>
            <option value="basketball">Basketball</option>
            <option value="baseball">Baseball</option>
        </select>


         <input type="submit" value="submit"></p>
     </form>
      </body>
      </html>
    <?php

          foreach($_POST["favsport"] as $val) {
             echo "<p>You chose $val </p>";
          }

      ?>

答案 1 :(得分:0)

你只有很少的拼写错误,因为我可以看到它在下面像

<select id="sport" name="favsport []" size="4" multiple>

用下面的行替换上面的行

<select id="sport" name="favsport[]" size="4" multiple>

错误: 错误位于name属性中,该属性具有额外的空白区域,如

name="favsport**here you having one space** []",它必须像name="favsport[]"

希望这能解决您的问题。 :)