dreno
dreno

Reputation: 13

check same value while loop

How can I check a while loop for same value on two specific column? If the same value exist on two columns then the output should be different than if there are no matches. This is the while statement I have right now:

Database connection:

<?php
$sql="SELECT id, name, phone, primaryfile FROM `users`";
$stmt=$generic->query($sql);
$count = $stmt->rowCount();
?>

While statement:

<?
while($data = $stmt->fetch(PDO::FETCH_ASSOC)) :
?>

The output:

<table>
    <tbody>
        <tr>
            <td><?php echo $data['id'];?>;<?php echo $data['name'];?>;<?php echo $data['phone'];?>;<?php echo $data['primaryfile'];?>;</td>
        </tr>
    </tbody>
</table>

This outputs each result as a row on my table.

But if same value exist on column id and primaryfile on multiple rows then it should merge those rows into one row and output like this:

<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>

Thanks in advance

Upvotes: 1

Views: 1838

Answers (2)

Suleman Ahmad
Suleman Ahmad

Reputation: 2113

First thing - Edit your query

<?php
$sql="SELECT id, name, phone, primaryfile FROM `users` ORDER BY id ASC";
$stmt=$generic->query($sql);
$count = $stmt->rowCount();
?>

Then you can track in your loop by keeping previous record:-

in while loop:

<?
$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;
    }   
?>

Upvotes: 1

Michael
Michael

Reputation: 12816

Change your query to GROUP BY id and primaryfile and use GROUP CONCAT (or alternatives on database systems that don't have it; you haven't specified which you're using) on the name and phone:

SELECT
  id,
  GROUP_CONCAT(name SEPARATOR '; ') AS name,
  GROUP_CONCAT(phone SEPARATOR '; ') AS phone,
  primaryfile
FROM
  users
GROUP BY
  id,
  primaryfile

Upvotes: 1

Related Questions