Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL counting most common value

Tags:

php

mysql

count

I have a MySQL database where users can list books they've read, want to read etc. I'm trying to write a query to find the most common book that users have listed.

My current query is:

$result = mysql_query("SELECT title, COUNT(title) AS counttitle FROM books GROUP BY title ORDER BY counttitle DESC LIMIT 1"); 
            echo "<p>The most popular book listed by members is $result</p>";

That seems (to me) to be the logical way to do it, and I can't see anything wrong with the syntax, but the result I'm getting is "The most popular book listed by members is Resource id #32"

Anyone any idea where I'm going wrong?

like image 851
BlissC Avatar asked Dec 29 '22 11:12

BlissC


2 Answers

I think you're missing this:

 $row = mysql_fetch_assoc($result)

The $result isn't actually the answer, it's a result resource containing the row that has the answer.

like image 58
dustmachine Avatar answered Jan 01 '23 00:01

dustmachine


Your query is fine, you need to read up on your PHP.

 result = mysql_query("SELECT title, COUNT(title) AS counttitle FROM books GROUP BY title ORDER BY counttitle DESC LIMIT 1");
 $row = mysql_fetch_assoc($result);
 echo "<p>The most popular book listed by members is " . row['title'] . "</p>";

Docs: http://us3.php.net/mysql_query

Return Values

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

like image 29
Scott Saunders Avatar answered Jan 01 '23 01:01

Scott Saunders