我有 2 个数据库表,如下所示:
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>';
但我还想将 banners
表中与每个位置的 banner_id
相匹配的 name
添加到列表中。所以我可以用每个 $row['location']
回显 $row['name']
:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"';
if($row['id'] == $location) { echo ' selected';} ;
echo '>' . $row['name'] . ' ' . $row['location'] . '</option>';
}
最佳答案
您需要一个 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>';
}
编辑:旁注
- > mysql_扩展名已弃用,您应该使用 PDO或 mysqli_
- 为了防止 SQL 注入(inject),您需要执行输入过滤和/或使用参数化查询。对于您的情况,最快的方法是将
$district_id
转换为整数。有关详细信息,请参阅 OWASP guide
关于php - 如何从一个下拉菜单的两个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22708338/