我的选择菜单每次显示每个记录的每个端口(伦敦,利物浦,都柏林),我只希望每个端口一次

时间:2012-05-10 12:37:12

标签: php mysql

这是查询,它返回我的巡航和票价表的搜索:

SELECT *, MIN(fares.offered) FROM cruises,fares 
WHERE cruises.departs > CURDATE() AND (cruises.destination LIKE %s OR 
  cruises.second_destination LIKE %s) AND 
  EXTRACT(YEAR_MONTH from cruises.departs) LIKE %s 
  AND cruises.fromport LIKE %s 
  AND cruises.ship LIKE %s AND cruises.live = 'Y' 
  AND fares.cruise_id = cruises.id 
GROUP BY fares.cruise_id ORDER BY cruises.departs, cruises.fromport"

我有一些跳转菜单,以便用户可以缩小搜索范围,例如上面的查询返回2012年7月的所有游轮,还有一些,一些来自伦敦,一些来自利物浦。

我的端口选择菜单中包含所有航行,如此

London
Liverpool
London
London
Liverpool

7月份每次返回的航班记录一次。

我只想要

London
Liverpool

这是选择代码:

<select name="jumpMenu3" id="jumpMenu3" onchange="MM_jumpMenu('parent',this,0)">
    <option value="">Select a port</option>
    <?php
    $port = ''; 
    mysql_data_seek($cruises, 0);
    while ($row_cruises = mysql_fetch_assoc($cruises)) { 
        if ($row_cruises['fromport'] != $port) {
            $port = $row_cruises['fromport'];
    ?>
    <option value="index.php?subj=2&destination=<?php 
       echo urlencode($row_cruises['destination']);
    ?>&departs=<?php 
      echo date('Ym',strtotime($row_cruises['departs']));
    ?>&port=<?php 
      echo urlencode($port);?>"<?php 
    if ($_GET['port'] == $row_cruises['fromport']) {
      echo "selected=\"selected\"";
    } 
    ?>><?php echo $port; ?></option>
    <?php } ;
    }
    if(mysql_num_rows($cruises) > 0) {
        mysql_data_seek($cruises, 0);
        $row_cruises = mysql_fetch_assoc($cruises);
    }
    ?>
    </select>

我考虑过GROUP BY,但我不能在我的搜索查询中使用它,因为很明显每个端口都有多个航班,也许我需要单独查询月份选项 - 或者我可以用PHP组?

1 个答案:

答案 0 :(得分:2)

最好的方法是检索端口名称的另一个查询,如下所示:

SELECT DISTINCT fromport FROM cruises WHERE cruises.departs > CURDATE()

您可以添加其他适用的条件。

第二种方法可以在PHP中完成:

$ports = array(); 
mysql_data_seek($cruises, 0);
while ($row_cruises = mysql_fetch_assoc($cruises)) { 
    if (!in_array($row_cruises['fromport'], $ports)) {
        $ports[] = $row_cruises['fromport'];
?>
<option value="index.php?subj=2&destination=<?php echo urlencode($row_cruises['destination']);?>&departs=<?php echo date('Ym',strtotime($row_cruises['departs']));?>&port=<?php echo urlencode($row_cruises['fromport']);?>"<?php if ($_GET['port'] == $row_cruises['fromport']) {echo "selected=\"selected\"";}?>><?php echo $row_cruises['fromport']; ?></option>
<?php
    }
}
if(mysql_num_rows($cruises) > 0) {
    mysql_data_seek($cruises, 0);
    $row_cruises = mysql_fetch_assoc($cruises);
}