用php显示mysql查询的结果

时间:2012-10-16 14:42:12

标签: mysql

我有以下代码:

$query = "SELECT ads.*,
       trafficsource.name AS trafficsource,
       trafficsource.id AS trafficsourse_id,
       FROM ads
           JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
        WHERE advertiserId = '$advertiser_id'";

        $mysqli = new mysqli();
        $mysqli->connect('localhost', 'root', '', 'adsbase');
        $result = $mysqli->query($query);
        while ($row = $result->fetch_assoc()) {
            echo "<h2>Traffic Sources: {$row['trafficsource']}</h2>";
        }

此代码显示结果如:

Traffic Sources: Example1
Traffic Sources: Example2
Traffic Sources: Example2
Traffic Sources: Example1
Traffic Sources: Example2
Traffic Sources: Example1

我想要的并且无法弄清楚的是显示如下结果:

Traffic Sources: Example1, Example2

所以没有重复,也在一行中。

4 个答案:

答案 0 :(得分:2)

你几乎拥有它:

    $result = $mysqli->query($query);
    $trafficeSources = array();
    while ($row = $result->fetch_assoc()) {
        $trafficSources[] = $row['trafficsource'];
    }

    echo '<h2>Traffic Sources: ' . implode(', ', $trafficSources) . '</h2>';

编辑:使用DISTINCT

查询

我假设您只需要流量来源名称,但如果需要,可以随意添加更多列。请记住,虽然DISTINCT适用于返回的所有行的不同组合,但如果其他选定列不同,则可能最终会出现重复的流量来源。

$query = "SELECT DISTINCT trafficsource.name AS trafficsource
          FROM ads
          JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
          WHERE advertiserId = '$advertiser_id'";

答案 1 :(得分:0)

在查询中使用'trafficsource'中的Group by,然后在while循环中将$ row ['trafficsource']的每个值连接到其他并在while循环之外回显它。

答案 2 :(得分:0)

尝试这个小解决方案:

     $trafic = array();
     while ($row = $result->fetch_assoc()) {
                if(!in_array($trafic)) $trafic[] = $row['trafficsource']
    }
    if(!empty($trafic)){
      echo  '<h2>Traffic Sources:' . imlode(',', $trafic) .'</h2>';
    }

答案 3 :(得分:0)

$trafficSources = array();
while ($row = $result->fetch_assoc()) {
    if(!in_array($row['trafficsource'], $trafficSources) {
        $trafficSources[] = $row['trafficsource'];
    }
}

echo "<h2>Traffic Sources: ".implode(', ', $trafficSources)."</h2>";