pierre273
pierre273

Reputation: 23

Foreach loop but print one time with multiple value

So I have in my database a table called "Clients" and an other one called "Pets". They are linked by an associative table which means that a "Clients" can have two "Pets".

I am using a FOREACH loop to display my client and pets but when a client have many pets, my foreach loop print everything, as many as the client have pets.

see here

here is my foreach loop

foreach ($files as $file) :
echo $file['address'];
endforeach

My problem is that I want to have everything diplayed normally except the "pets" (<?= $file['petName']; ?>) and see that the client have 2 pets..

like this :

Thanks for your help !

My SQL query

SELECT *
FROM clients
LEFT JOIN owners ON owners.idClients = clients.idClients
LEFT JOIN pets ON pets.idPets = owners.idPets
LEFT JOIN clientsdocs ON clientsdocs.idClients = clients.idClients
WHERE clients.idClients='$id'

Upvotes: 0

Views: 52

Answers (2)

pierre273
pierre273

Reputation: 23

Perfect, this what I wanted, thanks a lot !

here the modified code :

SELECT *, 
GROUP_CONCAT(DISTINCT petName ORDER BY petName) AS petsNames
FROM clients
LEFT JOIN owners ON owners.idClients = clients.idClients
LEFT JOIN pets ON pets.idPets = owners.idPets
LEFT JOIN clientsdocs ON clientsdocs.idClients = clients.idClients
WHERE clients.idClients='$id'

Upvotes: 1

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

You can change query like:

SELECT
    clients.*, 
    GROUP_CONCAT(petName) AS petsNames # implode pets names s into 1 string
FROM clients
LEFT JOIN owners ON owners.idClients = clients.idClients
LEFT JOIN pets ON pets.idPets = owners.idPets
LEFT JOIN clientsdocs ON clientsdocs.idClients = clients.idClients
GROUP BY clients.idClients # this is group all client's data in single row
WHERE clients.idClients='$id';

It's not solution, but can can give you an idea for best solution.

Upvotes: 0

Related Questions