dsizmmwnm56437180 2014-03-28 09:08
浏览 21
已采纳

如何从一个下拉菜单的两个表中获取数据

I have 2 database tables like so:

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:

$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. So I can echo out $row['name'] with each $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>';
}
  • 写回答

3条回答 默认 最新

  • douwei1408 2014-03-28 09:11
    关注

    You need a JOIN query. 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:

    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

    • mysql_ extension is deprecated, you should use PDO or mysqli_
    • In order to prevent SQL injection, you need to perform input filtering and/or use parameterized queries. Quickest way for your case is to cast $district_id to integer. For more information please see OWASP guide
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛