如何从 MySQL 中提出 PHP 中的 SELECTED 选项?
在我的更新表单中,我希望字段能够调用已存储的值。这在文本字段中非常简单,但对于我的下拉菜单 (),我在 PHP 读取已存储的用户名时遇到了问题。这是我的查询和代码:
$sql = "SELECT users.user_id, users.name FROM users";
$result = mysql_query($sql, $connection)
or die ("Couldn't perform query $sql <br />".mysql_error());
$row = mysql_fetch_array($result);?>
<label>Designated Person:</label> <select name="name" id="name">
<option value="<?php echo $row['user_id']?>" SELECTED><?php echo $row['name']?> - Current</option>
<?php
while($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['user_id']; if (isset($_POST['user_id']));?>"><?php echo $row['fullname']?></option>
<?php } ?>
其结果显示所有用户(根据需要)并让我选择一个用户,然后成功执行更改...但是“SELECTED”始终是我的数据库中的第一个用户,而不是第一个用户添加我的活动时选择的用户:(!!!
In my update form, I want the fields to recall the values that are already stored. This is very simple in a text field, but for my drop down () I'm having trouble with PHP reading the already stored name of user. Here is my query and code:
$sql = "SELECT users.user_id, users.name FROM users";
$result = mysql_query($sql, $connection)
or die ("Couldn't perform query $sql <br />".mysql_error());
$row = mysql_fetch_array($result);?>
<label>Designated Person:</label> <select name="name" id="name">
<option value="<?php echo $row['user_id']?>" SELECTED><?php echo $row['name']?> - Current</option>
<?php
while($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['user_id']; if (isset($_POST['user_id']));?>"><?php echo $row['fullname']?></option>
<?php } ?>
The result of this displays all of the users (as required) and lets me select a user then perform the change successfully...however the 'SELECTED' is always the first one in my database and never the user that was selected when my activity was added :( !!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您现在要做的是:
试试这个(假设
$curname
是当前选择的名称):What you're doing now is:
Try this (assuming
$curname
is the currently selected name):嗯...我认为你的代码不完整。例如,最后一个选项有一个不执行任何操作的 if 语句...并且您不应该将所选内容放在同一选择元素中的两个不同选项上。
如果没有其他人,第一个选项总是默认选择的,并且....对于 xhtml 尝试使用 selected="selected" 而不是 SELECTED
另外,您试图回显 $row['fullname'],但您的查询是获取列“名称”
Hmm... i think your code is not complete. Ex the last option got an if-statement that does nothing...and you should not put selected on two diffrent options in the same select element.
The first option is always default selected if no-one else is, and.... for xhtml try using selected="selected" instead of SELECTED
Also, you are trying to echo $row['fullname'], but your query is fetching column 'name'