0

这是我的数据:

select * from extension;
+---------+-------+
| ext_num | name  |
+---------+-------+
|  574324 | joe   |
|  564334 | sarah |
|  987652 | pete  |
+---------+-------+
3 rows in set (0.00 sec)

我正在尝试插入

selected="selected"

动态地同时遍历表。

<?php

$mysqli = new mysqli("localhost", "user", "pass", "db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if ($result = $mysqli->query("SELECT * FROM extension")) {
 print "<select>\n<option>select a value</option>\n";
    while ($row = $result->fetch_assoc()) 
{
        printf ("<option value=\"%s\">%s</option>\n", $row["ext_num"], $row["name"]);
    }
 print '</select>';
}
?>

实现以下内容的最简单/有效的方法是什么:

<option value="987652" selected="selected">pete</option>

(特别是:selected="selected")

使用与上述类似的代码进入我的循环?

4

2 回答 2

0

好的,假设您从中获得要选择的行,POST您可以在循环中放置一个条件while来检查特定的 post 变量

<?php

    $name = $_POST['name'];

    while ($row = $result->fetch_assoc()) 
    {
        if ($name==$row["name"])
            echo '<option value="'.$row["ext_num"].'" selected="selected">'.$row["name"].'</option>';
        else
            echo '<option value="'.$row["ext_num"].'">'.$row["name"].'</option>';
    }
?>
于 2013-08-20T21:00:09.417 回答
0

您可以使用此代码:

<?php

$mysqli = new mysqli("localhost", "cookie", "pass", "test_intranet");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$selItem = 987652 ;
if ($result = $mysqli->query("SELECT CONCAT('<option value=\"',`ext_num `,'\" ',IF(ext_num=$selItem,'selected=\"\"',' '),'>',`name`,'</option>') AS 'row' FROM extension")) {
 print "<select>\n<option>select a value</option>\n";
    while ($row = $result->fetch_assoc()) 
{
       echo $row['row'] ;
    }
 print '</select>';
}
?>

为了获得更高的性能并在查询中连续使用 selected="" 。

于 2013-08-20T20:48:31.550 回答