magcr23 Posted July 1, 2015 Share Posted July 1, 2015 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 - 2pc2 - 1pc3 - 0pc4 - 3 How can i order that by the number? I want this result: pc4 - 3 pc1 - 2 pc2 - 1 pc3 - 0 Quote Link to comment https://forums.phpfreaks.com/topic/297133-order-mysql-data-in-a-while-loop/ Share on other sites More sharing options...
Solution Barand Posted July 1, 2015 Solution Share Posted July 1, 2015 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" 1 Quote Link to comment https://forums.phpfreaks.com/topic/297133-order-mysql-data-in-a-while-loop/#findComment-1515348 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.