Jump to content


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


SUM & ORDER BY query

Recommended Posts

Hi guys,

Having a minor problem here. On my reports page, I want to display the top 5 books that people have chose.
In my database, i have 3 fields (Book, School, Hits). Inside my insert.php script, it automatically inserts a number 1 into the hits every time I submit the form.

On my reports page, I am able to list the books with the amount of hits they have had but I'm unable get them to display the highest first.



$link = mysql_connect("localhost", "username", "password") or die("Could not connect");
$db = mysql_select_db("database", $link) or die("Could not select database");


$result=mysql_query("INSERT INTO `books` VALUES ( '$book', '$school', '1') ");




$link = mysql_connect("localhost", "username", "password") or die ('My SQL Error: ' . mysql_error());
$db = mysql_select_db("database");

$result = mysql_query ( "SELECT Book, sum(Hits) FROM `books` GROUP BY 'Book' ") or die("SELECT Error: ".mysql_error());



print "<table width=400 border=3>\n";
while ($get_info = mysql_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td><font face=verdana size=3/>$field</font></td>\n";
print "</tr>\n";
print "</table>\n";

Share this post

Link to post
Share on other sites
Just use a column alias for the SUM() and then order by that desc.

Share this post

Link to post
Share on other sites


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.