shadowcaster Posted October 26, 2006 Share Posted October 26, 2006 Hi everyone. I have a search engine on my website that I wish to know what the most popular searches are. I would like to know if the mysql code below is the correct way of doing a 'most-popular-searches' query. Here is the code including using PHP:[code]//Find every unique search$queryA = mysql_query("SELECT DISTINCT(searches) FROM search_table");//create temporary table to hold search and number of times searched$queryB = mysql_query("CREATE TEMPORARY TABLE searches_count (searches VARCHAR(255), count INT);");//loop through the distinct searcheswhile ($row = mysql_fetch_array($queryA)){ //count how many times each search is in table $queryC = mysql_query("SELECT COUNT(searches) FROM search_table WHERE searches='".$row[0]."'"); //insert results into temporary table (extracts count from queryC) while($row2 = mysql_fetch_array($queryC)){ mysql_query("INSERT INTO searches_count VALUES('$row[0]','[$row2[0]');"); }}//sort and output the most popular searches$results = mysql_query("SELECT * FROM searches_count ORDER BY count");while($row = mysql_fetch_array($results)){ print $row[0]. " " .$row[1]. "<br>\n";}[/code]Am I doing this correctly or is there an easier way? Quote Link to comment https://forums.phpfreaks.com/topic/25120-most-popular-searches-method/ Share on other sites More sharing options...
btherl Posted October 26, 2006 Share Posted October 26, 2006 You can put all the complexity into sql like this:[code]SELECT searches, count(searches) as countFROM search_tableGROUP BY searchesORDER BY count DESCLIMIT 100[/code]The "group by searches" takes the place of your "select distinct" .. a "group by" will make the columns you group by distinct. But when you group results, you need to use an aggregate like count(), sum(), max() on any other values which were not grouped (in this case you just want to count how many times each "searches" appears).After that, the ordering and limiting is straightforward. That query will give you the top 100 searches. Quote Link to comment https://forums.phpfreaks.com/topic/25120-most-popular-searches-method/#findComment-114575 Share on other sites More sharing options...
shadowcaster Posted October 28, 2006 Author Share Posted October 28, 2006 That worked brilliantly! Thank you so much!! :D Quote Link to comment https://forums.phpfreaks.com/topic/25120-most-popular-searches-method/#findComment-115666 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.