Jump to content

Order mysql data in a while loop


Go to solution Solved by Barand,

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

  • Solution

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"

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.