使用PHP从表中的列中选择名称

时间:2015-11-20 09:47:39

标签: php mysql

我正在尝试从我拥有的表中获取业务类型,在上一页中我使用了此代码

$sql = "SELECT * FROM directorydata WHERE CompanyName LIKE :SearchTerm ORDER BY CompanyName ";

然而,这依赖于搜索词,我只想要使用foreach循环输出的类型列表。有几个企业,他们有相同的业务类型,我不希望这两次输出。

这是我的旧foreach循环,如果这有帮助,虽然这不应该改变任何东西

if ($stmt->rowcount() > 0) {
    foreach($stmt as $row) {
        $ResultsCounter++;
        $htmlResult .=  "<div class='col-md-6 well' style='margin'>" .
                            "<h4>". $row['CompanyName'] . "</h4>" .
                            "<p><strong><a href='/" . $row['UrlAlias'] .".htm'>" . $phoneDirectory->formatPhoneNumber($row['Number1']) ."</a></strong></p>" .
                        "</div>"; 

        if ($ResultsCounter == 8){
            $htmlResult .=  "<div class=''><a class='collapse-btn' href='#'>See more results</a><div class='span4 collapse-group'><div class='collapse'>"; 
        }
    }

    if ($stmt->rowcount() >= 8) $htmlResult .=  "</div></div></div>"; 


} else{
        $htmlResult .= "<h1 class='text-center'>Sorry no search results found please search again</h1>";
}
}

这里有任何帮助吗?

1 个答案:

答案 0 :(得分:2)

使用Group by typedistinct type

$sql = "SELECT * FROM directorydata
WHERE CompanyName LIKE :SearchTerm 
GROUP BY type
ORDER BY CompanyName ";

DISTINCT

$sql = "SELECT DISTINCT type FROM directorydata
WHERE CompanyName LIKE :SearchTerm 
ORDER BY CompanyName ";