从数据库填充下拉列表

时间:2010-09-02 14:22:31

标签: php database forms

我正在使用此代码重新填充数据库中的下拉列表:

      $city_id = 15;
  while($row = mysql_fetch_assoc($result)) { 
          $selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
          echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';

  }

它的工作就像魅力,但我的问题是它们是更优雅的解决方案吗?

4 个答案:

答案 0 :(得分:3)

除了改进代码的indentation之外,这很好。

$city_id = 15;
while($row = mysql_fetch_assoc($result))
{ 
    $selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
    echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}

答案 1 :(得分:1)

嗯,更优雅的解决方案是拥有一个“控制器”文件,可以获取所有城市,并将它们放入数组/对象列表/等等。然后,在“视图”文件中,迭代该变量。这样,您可以将演示文稿与逻辑分开一点。

在视图中:

<select name=student value=''>Student Name</option>
    <?php foreach($cities as $city): ?>
        <option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
    <?php endforeach; ?>
</select>

此外,我强烈建议您使用PDO进行数据库访问。

答案 2 :(得分:0)

  1. mysql_fetch_assoc到mysql_fetch_array
  2. 添加适当的评论
  3. 使用标准的php class ezsqlsimple class tuts

    $query="SELECT name,id FROM student";
    
    /* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
    
    $result = mysql_query ($query);
    echo "<select name=student value=''>Student Name</option>";
    // printing the list box select command
    
    while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
    echo "<option value=$nt[id]>$nt[name]</option>";
    /* Option values are added by looping through the array */
    }
    echo "</select>";//Closing of list box 
    

答案 3 :(得分:0)

我总是使用一个函数,因为选择框是我最终创建的东西......

function select($name, $default, $values, $style='', $param='') {
        $html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
        foreach($values as $i => $data) {
            if (isset($data['noFormat'])) { 
                $html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
                         (isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
            } else {
                $html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
                         (isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
            }
        }
        $html .= '</select>';
        return $html;                 
    }

然后循环查询以构建这样的数组:

$default[] = array('value' => '0',   'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {  
    $list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);

最后是一个创建HTML的例子:

select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');

希望它有所帮助!