2012-02-26 52 views
0

我需要一些帮助,在这里我的逻辑。我在我的选择框中填充数据库中的值。在我的下拉框中不显示重复值

如果存在,我回显值,否则我显示默认选项。

现在,例如,如果数据库的值是新泽西州,我不想在我的下拉框中第二次显示新泽西州。我怎么做?

<select name="location" class="field" > 

       <option value="<?php if(!empty($get_location)){ echo $get_location; } ?>"><?php if(!empty($get_location)){ echo $get_location; }?></option> 

       <option value="New Jersey">New Jersey</option> 

       <option value="New York">New York</option> 

       <option value="California">California</option> 
      </select> 
+0

New Jersey,New York and California are defaults? – elclanrs 2012-02-26 00:24:38

+0

也请看看使用模板引擎(我习惯了http://www.smarty.net/,但还有很多其他的([wikipedia](http://en.wikipedia.org/wiki/Template_engine_( web)#Comparison))),这将缓解开发PHP网页的生活 – 2012-02-26 01:50:57

回答

1

你让一个if语句中的每个选项字段,并检查数据库中的值选项字段的值相匹配,如果这样做,你echo "selected=\"true\""的选项字段。

有关代码示例见我的回答这个问题: retieve data from mysql and display in form

+0

感谢您的帮助......我认为Marc的答案是我期待的快速解决方案! – newbie 2012-02-26 01:14:45

0

如果想显示你的数据库值:

<?php 
    // You populate an array with the locations from your database 
    // As an example: 
    $options = array(1=>'New Jersey',2=>'Los Angeles'); 

    $html = '<select name="locations">'; 
    foreach($options as $id => $option) 
    { 
     $html .= '<option id="'.$id.'">'.$option.'</option>'; 
    } 
    echo $html.'</select>'; 
?> 

如果你想一些特别的东西发生在你的数据库值,但仍然加载默认值:

<?php 
    // You populate an array with the locations from your database 
    // As an example: 
    $options = array(1=>'New Jersey',2=>'Los Angeles'); 

    // Compare against your full list of locations 
    // As an example: 
    $locations = array(1=>'New Jersey',2=>'Los Angeles',3=>'California',4=>'London'); 

    $html = '<select name="locations">'; 
    foreach($options as $id => $option) 
    { 
     if(array_key_exists($id,$locations)) 
     { 
     // Enter your magic 
     } 
    } 
    echo $html.'</select>'; 
?> 
0

我会c稍微增加你的php代码以添加默认值,然后你可以使用jQuery过滤和删除重复项。如果有很多的选择,这可能不是最好的解决办法寿...

PHP

<select name="location" class="field"> 
    <?php if(!empty($get_location)): ?> 
     <option value="<?php echo $get_location; ?>"> 
      <?php echo $get_location; ?> 
     </option> 
    <?php else: ?> 
     // Defaults 
    <?php endif; ?> 
</select> 

jQuery的

var removeDup = function($select){ 
    var val = ''; 
    $select.find('option').each(function(){ 
     if ($(this).val() === val) { $(this).remove(); } 
     val = $(this).text(); 
    }); 
}; 
removeDup($('#yourSelect')); 
0

在一个请求到数据库中获取你的位置,将它们与默认值一起添加到数组中,如果只有一个位置如下所示,如果多个位置将它们解析为数组并将它们与默认值合并,则执行array_unique以获取摆脱重复并在循环中输出数组。

<select name="location" class="field"> 
    <?php 
     $output = array(1=>'New Jersey', 2=>'New York', 3=>'California', 4=>$get_location); 
     $options = array_unique($output); 

     foreach($options as $key => $value) { 
      echo '<option value="'.$value.'">'.$value.'</option>'; 
     } 
    ?> 
</select>