如何让 <option selected="selected"> 由 MySQL 和 PHP 设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2969762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:17:09  来源:igfitidea点击:

How to make <option selected="selected"> set by MySQL and PHP?

phpmysqlselectoption

提问by Binyamin

How to make <option selected="selected">set by MySQL and PHP?

如何<option selected="selected">通过 MySQL 和 PHP进行设置?

My code:

我的代码:

echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
    $r = mysql_fetch_array($rs);
    //if($year==$r["year"]){ $selected=' selected="selected"'; }//doesn't work so
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option>".$r["year"]."</option>";//<option$selected>...
    }
}
unset($tempholder);
echo '</select>';

回答by 2ndkauboy

Try this one:

试试这个:

    echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
    $r = mysql_fetch_array($rs);
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option".(($year==$r["year"])? ' selected="selected"' : '').">".$r["year"]."</option>";
    }
}
unset($tempholder);
echo '</select>';

It doesn't saves the state in a variable which you have to overwrite.

它不会将状态保存在您必须覆盖的变量中。

And I think the real error was the single equal sign in $year=$r["year"] and not wihtin the rest of the code.

我认为真正的错误是 $year=$r["year"] 中的单个等号,而不是其余代码。

回答by bobince

In addition to fixing the =/==gotcha, you can save yourself the array lookup and make the code simpler by asking the database to return each year only once in the query:

除了修复=/ ==gotcha 之外,您还可以通过要求数据库在查询中每年只返回一次来节省数组查找并使代码更简单:

<select>
    <?php $result= mysql_query('SELECT DISTINCT year FROM id ORDER BY year'); ?>
    <?php while($row= mysql_fetch_assoc($result)) { ?>
        <option <?php if ($row['year']==$year) { ?>selected="selected"<?php } ?>>
            <?php echo htmlspecialchars($row['year']); ?>
        </option>
    <?php } ?>
</select>

(You may not need htmlspecialchars()assuming that's a numeric year, but it's good practice always to HTML-escape any plain text you include in an HTML template. You can define a function with a shorter name to do the echo htmlspecialcharsto cut down on typing. )

(您可能不需要htmlspecialchars()假设这是一个数字年份,但总是对包含在 HTML 模板中的任何纯文本进行 HTML 转义是一种很好的做法。您可以定义一个具有较短名称的函数echo htmlspecialchars来减少输入。)

回答by Artefacto

You must define $selectedeverytime, and you were using the assignment operator instead of the comparison:

您必须$selected每次都定义,并且您使用的是赋值运算符而不是比较:

echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i = 0; $i < $nr; $i++){
    if($year == $r["year"]) { //not $year = $r["year"]
        $selected=' selected="selected"';
    }
    else {
       $selected = "";
    }
    $r = mysql_fetch_array($rs);
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option$selected>" . $r["year"] . "</option>";
    }
}
unset($tempholder);
echo '</select>';

回答by nomistic

Adding a new answer here for posterity, since the old code, which while correct at the time (actually mysqlidid exist, but many hosts didn't support PHP 5), is unfortunately using deprecated code. Instead of using mysql_extensions, here's a way to handle it using an object oriented approach which will work with mysqli_connections:

在这里为后代添加一个新答案,因为旧代码虽然在当时是正确的(实际上mysqli确实存在,但许多主机不支持 PHP 5),但不幸的是使用了不推荐使用的代码。mysql_这里不使用扩展,而是使用面向对象的方法来处理它,该方法将与mysqli_连接一起使用:

Here's the database connection

这是数据库连接

$conn = new mysqli($host, $username, $password, $dbname);

if  ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Assuming that the $yearvariable is coming from a form (though it could be used from GETor SESSIONor wherever)

假设$year变量从表单来的(尽管它可以从被使用GETSESSION或其它地方)

$year = $_POST['year'];

Here's the query for the option button (I have it broken out into different rows to make it a little easier to read):

这是选项按钮的查询(我将它分成不同的行以使其更易于阅读):

$result=$conn->query($sql);
    while($row = $result->fetch_assoc()) {    
        if ($row['year']==$year) {
            $selected = 'selected="selected"';
        }
        else {
            $selected = '';
        }   
        echo '<option value="'.$row['year'].'" '. $selected . '>"'
            . $row['year'] .'</option>';
    }