如何在两个特定列上检查while循环的相同值? 如果两列上存在相同的值,则输出应该与没有匹配时的输出不同。这是我现在的声明:
数据库连接:
<?php
$sql="SELECT id, name, phone, primaryfile FROM `users`";
$stmt=$generic->query($sql);
$count = $stmt->rowCount();
?>
while声明:
<?
while($data = $stmt->fetch(PDO::FETCH_ASSOC)) :
?>
输出:
<table>
<tbody>
<tr>
<td><?php echo $data['id'];?>;<?php echo $data['name'];?>;<?php echo $data['phone'];?>;<?php echo $data['primaryfile'];?>;</td>
</tr>
</tbody>
</table>
这会将每个结果作为一行输出到我的桌子上。
但是如果多行上的 id 列和 primaryfile 上存在相同的值,那么它应该将这些行合并为一行并输出如下:
<table>
<tbody>
<tr>
<td><?php echo $data['id'];?>;<?php echo $data['name'];?>;<?php echo $data['name of second row having same id and primaryfile'];?>;<?php echo $data['phone'];?>;<?php echo $data['phone of second row having same id and primaryfile'];?>;<?php echo $data['primaryfile'];?>;</td>
</tr>
</tbody>
</table>
提前致谢
答案 0 :(得分:1)
将您的查询更改为GROUP BY
id
和primaryfile
并使用GROUP CONCAT
(或者在没有它的数据库系统上的备选方案;您尚未指定哪个“正在使用”name
和phone
:
SELECT
id,
GROUP_CONCAT(name SEPARATOR '; ') AS name,
GROUP_CONCAT(phone SEPARATOR '; ') AS phone,
primaryfile
FROM
users
GROUP BY
id,
primaryfile
答案 1 :(得分:1)
首先 - 编辑您的查询
<?php
$sql="SELECT id, name, phone, primaryfile FROM `users` ORDER BY id ASC";
$stmt=$generic->query($sql);
$count = $stmt->rowCount();
?>
然后你可以通过保留以前的记录来跟踪你的循环: -
在while循环中:
<?
$previous_id = $previous_pfile = 0;
while($data = $stmt->fetch(PDO::FETCH_ASSOC)) :
$new_id = $data['id'];
$new_primary_file= $data['primaryfile'];
if($previous_id == $new_id && $previous_pfile == $new_primary_file){
// do your stuff for multiple rows
}else{
// do your steps for single records
$previous_id = $new_id;
$previous_pfile = $new_primary_file;
}
?>