In need of help
In need of help

Reputation: 35

Count or Sum most sold product from MySQL

I have a MySQL table with each product I sold, the database looks like this:

ID CODE QUANTITY PRICE PAID EARNINGS

As you can see its very basic, I sell a product and it gets saved there.

The problem now is my boss told me to show a page with the most sold products order by most sold to less sold.

In this case what I have to do is to count the QUANTITY field

OK here we go

<?php
$letsdoit = mysqli_query($database, "SELECT * FROM `sales` SUM(quantity) AS `quantity` order by `quantity`");
while($show= mysqli_fetch_assoc($letsdoit )){
 ?> 

Now we show the results of all sold products ordered by most sold (quantity) using the sum(quantity) and then we show the results like this

CODE <?php echo $mostrar['code'] ?> QUANTITY <?php echo $mostrar['quantity'] ?>

we close the WHILE

<?php }?>

The problem is, it is counting all products sold, tried another way and get

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in

I never did a query so complicated like this Can anyone give me a hand to see how it must be done?

Thanks a lot for any idea or help

Upvotes: 2

Views: 3789

Answers (1)

alamnaryab
alamnaryab

Reputation: 1484

make your query as following

select code, count(*) as count from sold
group by code
order by count desc

Upvotes: 5

Related Questions