我有两个数据库表,如下所示:
CREATE TABLE IF NOT EXISTS `banners` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`long_name` varchar(50) NOT NULL,
`visible` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
和
CREATE TABLE IF NOT EXISTS `locations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`banner_id` int(2) NOT NULL,
`district_id` int(2) NOT NULL,
`number` int(5) NOT NULL,
`location` varchar(50) NOT NULL,
`visible` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=511 ;
我使用下面的代码根据他们的district_id提取位置列表并创建一个下拉菜单:
$query = 'SELECT id, banner_id, location FROM locations WHERE district_id =' . $district_id;
$result = mysql_query($query, $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"';
if($row['id'] == $location) { echo ' selected';} ;
echo '>' . $row['location'] . '</option>';
}
echo '</select>';
但我还要在列表中添加name
表中与每个位置banners
匹配的banner_id
。所以我可以用$row['name']
:
$row['location']
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"';
if($row['id'] == $location) { echo ' selected';} ;
echo '>' . $row['name'] . ' ' . $row['location'] . '</option>';
}
答案 0 :(得分:4)
您需要一个JOIN查询。请尝试以下方法:
$query = 'SELECT l.id, l.banner_id, l.location, b.name
FROM locations l
INNER JOIN banners b ON (l.banner_id = b.id)
WHERE district_id =' . $district_id;
现在,结果集中同时包含name
和location
:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"';
if($row['id'] == $location) { echo ' selected';} ;
echo '>' . $row['name'] . ' ' . $row['location'] . '</option>';
}
编辑:旁注
$district_id
转换为整数。有关详细信息,请参阅OWASP guide 答案 1 :(得分:0)
使用JOINS获取两个表的相应标题名称 与选择横幅一样。,locations。其中locations.banners = banner.id
答案 2 :(得分:0)
这是mysql查询,它将执行所需的结果。