[英]PHP HTML select box selected from MYSQL
一个简单的代码,在选择框中插入团队列表。 我想设置一个ID为SELECTED的团队,即在HREF中
http://localhost/teams.php?id=7&years=2011&cups=8
<?php
$query = "select distinct t.team_id,t.team from teams t,years y,cups c where t.team_id=c.team_id and y.year_id=$_GET[years] and c.cup_id=$_GET[cups] ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>
问题是我设置了team_id = $ _ GET [id],它只显示一个团队。 我希望选择团队= 7,但其他人仍在选择框中显示
首先,永远不要将原始数据插入SQL查询。 您正在要求SQL注入。 其次,您缺少$ _GET变量的引号,例如,在SQL查询中,您当前使用$_GET[id]
访问id。 这将不起作用,将id
封装在引号中,例如$_GET['id']
。 第三,逃避您的数据!
现在不建议使用mysql_*
函数。 您不应该在新代码中使用它们。 相反,请研究PDO或MySQLi功能。 同时查看准备好的查询。
这应该是您的代码:
<?php
$years = mysql_real_escape_string($_GET['years']);
$cups = mysql_real_escape_string($_GET['cups']);
$query = "SELECT distinct t.team_id, vt.team
FROM teams t,years y,cups c
WHERE t.team_id = c.team_id
AND y.year_id = '{$years}'
AND c.cup_id = '{$cups}'
ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
// The line below specifies whether the option should be selected.
$selected = $row['team_id']==$_GET['id'] ? 'selected="selected"' : '';
$option .= '<option ' . $selected . ' value= "' . $row['team_id'] . '">' . $row['team'] . '</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>
请注意,您容易受到SQL注入的攻击。 请参阅: 如何防止PHP中的SQL注入?
如此说来,您需要使用一个条件语句,将$row["team_id"]
与$_GET["ID"]
。
while($row = mysql_fetch_assoc($res))
{
if($row["team_id"] == $_GET["ID"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'" '.($row['team'] == 7 ? 'selected="selected"': '').'>'.$row['team'].'</option>';
}
将$ _GET中的ID与$ row ['team_id']进行比较。
while($row = mysql_fetch_assoc($res))
{
if($row['team_id'] == $_GET["id"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
我只关注循环部分:
while($row = mysql_fetch_assoc($res))
{
$selected = (isset($_GET['team_id']) && $row['team_id'] == $_GET['team_id']) ? 'selected' : '';
$option .= '<option value = "'.$row['team_id'].'" selected="'. $selected .'">'.$row['team'].'</option>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.