PHP没有从while循环中选择正确的值

时间:2019-07-16 09:51:25

标签: php html

我对while循环有疑问。我在循环中有一个选项标签和隐藏值,该选项标签可在下拉列表中正常使用,但隐藏值与所选下拉列表不匹配。

这是我的代码:

<?php 
session_start();
require 'config.php';
$option1 = '';
$idseason='';
$season = '';

$query1 = "select id,description from codemaster_local where codeclass = 'season' and description like '%1st%' group by description";
$result1 = mysqli_query($doa,$query1);
while($row1 = mysqli_fetch_array($result1)) {
$option1 .= "<option value='".$row1['description']."'>".$row1['description']."</option>";
$hidden = "<input type=hidden name=id value='".$row1['id']."'>";
}

if(isset($_POST['submit'])) {
 $season = $_POST['season'];
 $idseason = $_POST['id'];

 echo "Season :"; echo $season;echo "<br>";
 echo "ID : ";echo $idseason;
    }
?>

<html>  
      <head>  
           <link href="style/style.css" rel="stylesheet" type="text/css">
           <link href="style/sty.css" rel="stylesheet" type="text/css">
           <link href="style/dropdown.css" rel="stylesheet" type="text/css">
      </head>  
      <body>  
          <form class="form-style-9" action="" method="post">
            <table>

                <tr><td><b>Season:</b></td>
                    <td> <select name="season" class="select-css">
                         <?php  echo $option1; ?>
                        </select>      
                        <?php  echo $hidden; ?>
                    </td>
                </tr>
            </table><br>
            <input type="submit" value="Search" name="submit"> 
          </form>  
      </body>  
 </html>  

enter image description here

enter image description here

例如,2005年第1季的ID应该是24800,但是它选择了最后一个ID30539。我选择了任何一个季节,仍然选择了最后一个ID。有什么办法可以解决这个问题?

2 个答案:

答案 0 :(得分:0)

$hidden在您这段时间内的每个循环中都被覆盖。结果是一个名称为:id的隐藏字段,其中包含检索到的最后一行id的值。那就是您提交后获得的价值。

while($row1 = mysqli_fetch_array($result1)) {
    $option1 .= "<option value='".$row1['description']."'>".$row1['description']."</option>";
    $hidden = "<input type=hidden name=id value='".$row1['id']."'>";
}

我建议您将option的value属性更改为$row1['id']

while($row1 = mysqli_fetch_array($result1)) {
    $option1 .= "<option value='".$row1['id']."'>".$row1['description']."</option>";
}

这样,$_POST['season']将保存所选季节的相应ID。

答案 1 :(得分:-1)

尝试将id放在选项标签中,而不是隐藏的标签中:

while($row1 = mysqli_fetch_array($result1)) {
        $option1 .= "<option value='".$row1['description']."' id='".$row1['id']."'>".$row1['description']."</option>";
}