The Little Guy
03-25-2006, 04:23 PM
I need to get the last 5 entries from my MySQL database, How would I do it using a loop?
|
Click to See Complete Forum and Search --> : Getting Certain Rows From MySQL The Little Guy 03-25-2006, 04:23 PM I need to get the last 5 entries from my MySQL database, How would I do it using a loop? Speedydomain 03-25-2006, 05:20 PM How is the database sorted? Is it by id? or timestamp? NogDog 03-25-2006, 05:43 PM $result = mysql_query("your query here"); $numRows = mysql_num_rows($result); if($numRows > 5) { mysql_data_seek($result, $numRows - 5); } while($row = mysql_fetch_assoc($result)) { // do whatever you want with $row } chazzy 03-25-2006, 06:49 PM another way is to sort descending. SELECT column_list FROM your_table [where conditions, group by] ORDER BY [the key you're sorting on] ASC This will give the output backwards. You have to understand that a database has no concept of "the last 5 entries". You don't know how they're stored. You can sort the results on a particular column and in a for loop only get the 5 rows in question. The Little Guy 03-25-2006, 06:53 PM Here is what I did: $result = mysql_query("SELECT urltitle,description,menu1,url FROM search WHERE urltitle='$title' AND description='$desc' AND menu1='$menu' AND url='$url'"); $numRows = mysql_num_rows($result); if($numRows > 5) { mysql_data_seek($result, $numRows - 5); } while($row = mysql_fetch_assoc($result)) { // do whatever you want with $row echo $title; } It didn't display any thing NogDog 03-25-2006, 07:23 PM echo $row['urltitle']; chazzy 03-25-2006, 07:29 PM do you have some kind of primary key or something that you can actually order your results on? If so I'd do something like this: $sql = "SELECT urltitle,description,menu1,url FROM search WHERE urltitle='$title' AND description='$desc' AND menu1='$menu' AND url='$url' ORDER BY ID DESC"; $result = mysql_query($sql) or die("Query: ".$sql."\n<br />Failure to execute the above sql statement: ".mysql_error()); for($i=0;$i<5;$i++){ $row = mysql_fetch_assoc($result); echo $row['urltitle']; echo "\n<br />"; } You'll have to have $title,$menu,$url, $desc already defined on your page for this to work and verify that they are all EXACT matches, based on how your query is written. The Little Guy 03-25-2006, 07:29 PM I just realized that It displays the last five, but within those results, can I reverse the order, so the very last result on the MySQL database is displayed first? The Little Guy 03-26-2006, 12:47 AM Thanks chazzy, I was trying NogDogs way, and just couldn't get it in decending order, now it works thanks! webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |