PHP PDO组按列名称查询结果 [英] PHP PDO group query results by column name
本文介绍了PHP PDO组按列名称查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下PDO查询返回以下结果:
The following PDO query is returning the results below:
$db = new PDO('....');
$sth = $db->prepare('SELECT ...');
这些是结果:
name curso
ABC stack
CDE stack
FGH stack
IJK stack
LMN overflow
OPQ overflow
RST overflow
我需要构建如下的HTML:
I need to build the HTML like:
<p>stack</p>
ABC<br/>
CDE<br/>
...<br/>
<p>overflow</p>
LMN<br/>
OPQ<br/>
这是我正在尝试的:
$sth->execute();
//$curso = $sth->fetch();
$id = $sth->fetchColumn(1);
echo "<p>".mb_convert_encoding($id,'utf-8', 'iso-8859-1').'</p>';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo (mb_convert_encoding($row['name'],'utf-8', 'iso-8859-1')).'<br/>';
}
但这将删除每个组的名字,例如:
But this is removing the first name of each group, like:
<p>stack</p>
CDE<br/>
...<br/>
推荐答案
也许您可以尝试使用以下代码来打印结果:
Maybe you can try this kind of code to print the result:
$sth->execute();
$curso = '';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
if ($row['curso'] !== $curso) {
$curso = $row['curso'];
echo '<p>' . mb_convert_encoding($curso, 'utf-8', 'iso-8859-1') . '</p>';
}
echo mb_convert_encoding($row['name'], 'utf-8', 'iso-8859-1') . '<br />';
}
这篇关于PHP PDO组按列名称查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文