如何选择< select>数据库声明? [英] How to select a <select> statement from database?

查看:127
本文介绍了如何选择< select>数据库声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定如何正确地说出问题 - 但这只是出于真正的兴趣而已。不断,我不得不从数据库加载信息,并预先填充一个表单。因此,在文本框的情况下,它很容易,我只需设置值:

< input type =textvalue =< ; = $ foo的;?>中然而,当我来选择框时,我发现我的代码变得相当sl,,因为我需要放置一个名称为'foo'的文件选中值在该行的某处。所以真的有两种选择,我不喜欢这两种:

  $ one = $ two =; 
switch($ myval){
case1:$ one =selected;
case2:$ two =selected;


然后在HTML中:

 < select name =myval> 
< option value =1<?= $ one;?>> One< / option>
< option value =1<?= $ two;?>> Two< / option>
< / select>

或者另一种选择是在select的中间放置一个简写if语句:

 < select name =myval> 
< option value =1<?=($ myval ==1)? selected:;?>> One< / option>
< option value =1<?=($ myval ==2)? selected:;?>>两个< / option>
< / select>

看起来稍微干净些,但它仍然让我感到不安。



任何人都有更高效的方法来做到这一点?它只是一个是/否下拉框,我必须为每个值编写愚蠢的if语句。



同样的问题也适用于复选框。

解决方案

作为Quentin的一个补充(只是一些代码来帮助你我倾向于使用数组,如下所示:

 < select name =myval> 
<?php
$ options = array(
1=>One,
2=>Two
);
foreach($ options as $ value => $ text){
echo'< option value ='。$ value。''。 ($ myval == $ value?'selected':'')。 '>'。 $ text。 < /选项>;
}
?>
< / select>


I wasnt quite sure how to word the question correctly - but this is merely just out of interest really. Constantly I am having to load information from a database and pre-populate a form with the values. So in the case of the textbox, its easy, i simply set the value:

<input type="text" value="<?=$foo;?>" name="foobar">

However when I come to select boxes I find my code gets quite sloppy, as I need to place a selected value in the line somewhere. So really I have two options, both of which I dislike:

$one = $two = "";
switch ($myval) {
  case "1": $one = " selected";
  case "2": $two = " selected";

}

and then in the HTML:

<select name="myval">
<option value="1"<?=$one;?>>One</option>
<option value="1"<?=$two;?>>Two</option>
</select>

Or the other option is to place a shorthand if statement in the middle of the select:

<select name="myval">
<option value="1"<?=($myval=="1") ? " selected" : "";?>>One</option>
<option value="1"<?=($myval=="2") ? " selected" : "";?>>Two</option>
</select>

Which looks slightly cleaner, however it still bugs me.

Anyone got any much more efficent ways of doing this? its even more annyoing when It is just a Yes/No drop downbox and I have to write stupid if statements for each value.

The same question applies to checkboxes as well.

解决方案

As an addition to Quentin (just some code to help you out), I tend to use arrays as well, like this:

<select name="myval">
    <?php
        $options = array(
            "1" => "One",
            "2" => "Two"
        );
        foreach ($options as $value => $text) {
            echo '<option value="' . $value . '"' . ($myval == $value ? ' selected' : '') . '>' . $text . '</option>';
        }
    ?>
</select>

这篇关于如何选择&lt; select&gt;数据库声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆