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 Link to comment https://forums.phpfreaks.com/topic/297133-order-mysql-data-in-a-while-loop/ Share on other sites More sharing options...
Barand Posted July 1, 2015 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" 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
Archived
This topic is now archived and is closed to further replies.