Web Hosting Talk







View Full Version : MYSQL Query - Slect 10 rows (help)


waturl
01-26-2007, 12:15 PM
Hello,

I'm doing a search engine (connectingwith mysql), i'm saving in the database what peope search, may be this word "hack" searched 16 time. means in 16 rows.

the problem, how can i print top 10 search...?

// I connected to localhost and DB
//$result = mysql_query("select * from TableName");
//$affecteds = mysql_affected_rows(); /it can get 159/

//while($row = mysql_fetch_array($result)){
print $row['fieldName']; //it prints all rows

Iwant to print just the TOP 10

Thanks for your help

submenu
01-26-2007, 12:30 PM
Try this:

$sql = "SELECT count(fieldname) as totalsearches, fieldname FROM tablename GROUP BY fieldname ORDER BY totalsearches DESC LIMIT 10"

$result = mysql_query($sql, $conn);

while ($row = mysql_fetch_assoc($result)) {
echo $row["fieldname"] . " was searched for " . $row["totalsearches"] . " times.<br />";
}

waturl
01-26-2007, 12:52 PM
I see, but there's no a totalsearches field.

exemple this is the tabke

tableName = music
Fields:
ID: int - auto_increment - PRIMARY
word: varchar //search words will be saved here
date: varchar // dateand time for searching

should i add a new field..?

howwillbe the code..?

Xeentech
01-26-2007, 07:31 PM
"SELECT count(fieldname) as totalsearches" selects a count of rows, and names this make-believe column 'totalsearches'.

Just try that query first, fieldname should be 'word' I guess.

waturl
01-26-2007, 10:27 PM
I could do it but other way.

anyway, Thanks alot