[英]How to get data from two tables for one drop-down menu
I have 2 database tables like so: 我有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 ;
And: 和:
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 ;
I use the code below to pull a list of locations based on their district_id and create a drop-down menu: 我使用下面的代码根据其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>';
But I'd also like to add to the list the name
from the banners
table that matches the banner_id
for each location. 但我也想将与每个位置的
banner_id
相匹配的banners
表中的name
添加到列表中。 So I can echo out $row['name']
with each $row['location']
: 所以我可以在每个
$row['location']
回显$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>';
}
You need a JOIN query. 您需要一个JOIN查询。 Try following:
请尝试以下操作:
$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;
Now you have both name
and location
in your resultset: 现在,您的结果集中有
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>';
}
Edit : sidenotes 编辑 :旁注
$district_id
to integer. $district_id
强制转换为整数。 For more information please see OWASP guide Use JOINS inorder to get the corresponding banner name for two tables Like select banners. 使用JOINS来获取两个表(如选择横幅)的相应横幅名称。 ,locations.
,地点。 where locations.banner_id=banner.id
其中location.banner_id = banner.id
Here is mysql query which will excute desire results. 这是将执行期望结果的mysql查询。
$query = "select locations.id,
locations.banner_id,
locations.location,
banners.name,
banners.id
from locations, banners
WHERE banners.id=locations.banner_id
and district_id =" . $district_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.