Jump to content

Order mysql data in a while loop


magcr23

Recommended Posts

Hi guys, i have this code:

$u = mysqli_query($con, "SELECT * FROM `produtos` ");
while($uu = mysqli_fetch_assoc ($u)){
$nome_Produto = $uu['nome'];
$contagem = mysqli_query($con, "SELECT COUNT(*) as contagem FROM `carrinho` WHERE produto = '$nome_Produto' ");
$i = mysqli_fetch_array($contagem);		
echo $nome_Produto . ' - ' . @$i[contagem] . '<br/>';
}

That's the result:

pc1 - 2
pc2 - 1
pc3 - 0
pc4 - 3

 

How can i order that by the number? I want this result:

pc4 - 3

pc1 - 2

pc2 - 1

pc3 - 0

Link to comment
https://forums.phpfreaks.com/topic/297133-order-mysql-data-in-a-while-loop/
Share on other sites

Do not run queries in loops. Create a single query using a JOIN.

SELECT p.nome
    , COUNT(c.produto) as contagem
FROM produtos p
    LEFT JOIN carrinho c ON c.produto = p.nome
GROUP BY nome
ORDER BY contagem DESC

Loop through the results echoing "nome" and "contagem"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.