I have links and hits stored in my DB. Im trying to display a list of the most popular links (by hits) on my page in descending order. ie. linkA 384 hits linkB 263 hits linkC 188 hits etc... Here's what I have now: $popular = mysql_query("SELECT hits, link FROM links ORDER BY hits DESC"); echo $popular; Code (markup): Its not working and Im not too good with MySQL so I was wondering if someone could give me a quick hand. Also, I would like to limit the query to the top 20 results. Thanks in advance for any assistance.
use the LIMIT keyword to limit... e.g. LIMIT 20 at the end of your statement. What error are you getting? because it looks fine to me.
You are selecting the entries from the DB just fine, for limiting just use LIMIT: $popular = mysql_query("SELECT hits, link FROM links ORDER BY hits DESC LIMIT 0,20"); PHP: But your error is, because $popular is an Array and the "echo" function will only output "Array". You need to fetch the array and output it until the array is over. while ($row = mysql_fetch__array($popular) { //get data into array then use it untill there are no more rows to retrieve. echo $row[link]; } PHP: The above will go through the array and "echo" all the links in order until they are over. You can use different formatting like tables and cells for each link - you can do that by echo-ing the required code around the echo $row[link];, just remember that the whole part between the while() function will be repeated as many times as there are links. Hope I was useful, feel free to give rep if I was.
Thanks for the info, looks great, only Im getting an unexpected { error when I use it. Here's what I have: $popular = mysql_query("SELECT hits, link FROM links ORDER BY hits DESC LIMIT 0,20"); while ($row = mysql__fetch_array($popular){ echo $row[link]; } Code (markup): Still not working unfortunately.
You're forgetting to close a parenthesis after $popular. Here's the correct code: $popular = mysql_query("SELECT hits, link FROM links ORDER BY hits DESC LIMIT 0,20"); while ($row = mysql__fetch_array($popular)){ echo $row[link]; } PHP:
Also, it should be "mysql_fetch_array", not "mysql__fetch_array". You used a double underscore after "mysql" and it should be one.