如何使用$ _GET从url获取变量并将其设置为下拉列表的默认值

时间:2017-11-30 04:02:04

标签: php

在选择下拉列表中,我正在尝试使用$ _GET []从URL获取变量,并且下拉选择的值将基于来自URL的值get。  不知怎的,它失败了,有什么想法吗?

<select name="ForceSelection">
  <option value="default" >Select Case</option> 
  <?php
    include('connect-db.php');

    $sql = "SELECT DISTINCT(typename3),id AS id,typename3 FROM vaccinetype";

    $result = mysql_query($sql);

    while ($row = mysql_fetch_array($result)) {
      echo "<option value='" . $row['id'] . "' if ($row['id'] == '$_GET['typeid']') echo 'selected="selected"'; ?> >" . $row['typename3'] . "</option>";
    }
 ?>
 </select>

2 个答案:

答案 0 :(得分:1)

很难阅读该代码。如果你这样说的话,我认为它会更清晰可读:

 <select name="ForceSelection">
 <option value="default" >Select Case</option> 
 <?php

// get a value from typeid in URL 
$typeid = $_GET['typeid'];

include('connect-db.php');

$sql = "SELECT DISTINCT(typename3),id AS id,typename3 FROM vaccinetype";

$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {

  $id = $row['id']; 

  $selected = '';

  if ($id == $typeid) {
  $selected ='selected=selected';
  } 

    echo "<option value='$id' $selected>";
    echo htmlentities($row['typename3']);
    echo "</option>";
}
 ?>
 </select>

请注意我添加了htmlentities函数,因为数据库中的字符串可能包含一些转义HTML输出的字符。

答案 1 :(得分:-1)

看起来您的if语句不是可执行代码(它写在字符串中)。也许你的迭代代码应该是这样的。

while ($row = mysql_fetch_array($result)) {
      $id = $row['id'];
      $typeId = $_GET['typeid'];
      $selected = '';
      if ($id == $typeId) {
         $selected = 'selected="selected"';
      }
      echo "<option value='".$id."' ".$selected." >". $row['typename3']."</option>";
    }