Forum Moderators: open

Message Too Old, No Replies

Setting a Query Cap

         

Jeremy_H

6:53 pm on Dec 8, 2006 (gmt 0)

10+ Year Member



Hello,

I'm sending a query to my database to get some information to build an array:

$result=mysql_query("SELECT * FROM table_name");
$row=mysql_fetch_array($result);
$list=array();
while($row=mysql_fetch_array($result)) array_push($list,array($row['x'],$row['y'],$row['z']));

Later in my page I'll output a list like this:

for($i=1;$i<20;$i++) echo "$hot[$i-1][0], $hot[$i-1][1], $hot[$i-1][2]";

The thing is, I only need the top 20 rows form my table, but I'm having the script read everything in the database and putting that information in the array.

I think this is my weak spot:

$result=mysql_query("SELECT * FROM table_name");

How can I change that to limit it to just the top 20 records?

Thanks so much

FalseDawn

11:08 pm on Dec 8, 2006 (gmt 0)

10+ Year Member



Use a LIMIT clause (with an ORDER BY, otherwise the "top" 20 records will have no real meaning)
eg
SELECT * FROM table_name ORDER BY orderfield [DESC] LIMIT 20

LifeinAsia

11:25 pm on Dec 8, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



$result=mysql_query("SELECT TOP 20 * FROM table_name");

[EDIT] Oops, sorry- that will apparently only work if you're using MS-SQL as TOP is not part of the ANSI standard.

[edited by: LifeinAsia at 11:31 pm (utc) on Dec. 8, 2006]