选择包含SQL的选项

时间:2012-08-13 21:12:21

标签: sql select option

我有以下内容:

 `<select name="year" size="1" class="input" id="year" onChange="window.focus();" style="BACKGROUND-COLOR: #f7ed79; COLOR: #000000; font-family: Arial; font-size: 10px; width:60px;"> 
  <?php
  $sql = mysql_query("SELECT * FROM years");      
         while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
         echo("<option "); if($year==$row['year']) {echo "selected='selected'";}  
         echo ("value=\""); echo($row['year']); echo("\">"); echo($row['year']); 
         echo("</option>");
         };
         ?>
     </select>`

这给了我多年的选择权。但我希望有可能在年份编号之前查看SELECT YEAR,无论年份是什么。

这里有任何帮助吗?

由于

2 个答案:

答案 0 :(得分:0)

我希望我能理解它。

第一个选项:

<select name="year" size="1" class="input" id="year" onChange="window.focus();" style="BACKGROUND-COLOR: #f7ed79; COLOR: #000000; font-family: Arial; font-size: 10px; width:60px;">
<option selected="selected" disabled="disabled">Select year:</option>
<?php
      $sql = mysql_query("SELECT * FROM years");      
             while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
             echo("<option "); if($year==$row['year']) {echo "selected='selected'";}  
             echo ("value=\""); echo($row['year']); echo("\">"); echo($row['year']); 
             echo("</option>");
             };
 ?>
 </select>

第二个选项:

<select name="year" size="1" class="input" id="year" onChange="window.focus();" style="BACKGROUND-COLOR: #f7ed79; COLOR: #000000; font-family: Arial; font-size: 10px; width:60px;">
<optgroup label="Select year:">
<?php
      $sql = mysql_query("SELECT * FROM years");      
             while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
             echo("<option "); if($year==$row['year']) {echo "selected='selected'";}  
             echo ("value=\""); echo($row['year']); echo("\">"); echo($row['year']); 
             echo("</option>");
             };
 ?>
</optgroup></select>

答案 1 :(得分:0)

这可能会让它更容易阅读。此外,您应该考虑使用mysqli_或PDO函数。

<select id="year" class="input" name="year" onchange="window.focus();" style="background-color: #f7ed79; color: #000000; font-family: Arial; font-size: 10px; width:60px;">
<?php
  $sql = mysql_query("SELECT * FROM years") or die(mysql_error());

  while ($row = mysql_fetch_assoc($sql))
  {
    $selected_value = '';

    //not sure where $year is populated
    if($row['year'] == $year)
    {
      $selected_value = ' selected="selected"';
    }
?>
     <option value="<php echo $row['year'] ?>"<?php echo $selected_value ?>><php echo $row['year'] ?></option>
<?php
     };
?>
</select>