Jump to content


Photo

Loops in php


  • Please log in to reply
3 replies to this topic

#1 essjay_d12

essjay_d12
  • Members
  • PipPipPip
  • Advanced Member
  • 121 posts

Posted 14 March 2006 - 05:38 PM

I want to pull out the latest 10 results from my database, but im just not sure, i was thinking like this...

loop (1 to 10) {

query = Select NAME,.,..,.,..,DATE FROm database ORDER BY DATE

ECHO RESULTS

}

But I think the above structure (obviousy not code) is still wrong, wont that above structure when implemented in php just pull out 10 of the same ones (i.e the latest one only) and not the latest 10!

PLease help

Thanks


#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 14 March 2006 - 05:46 PM

Just do your normall mysql query like so:
<?php

//database connection code goes here

$sql = "SELECT name, email, date From users ORDER BY date";
$result = mysql_query($sql) or die("Error with query " . mysql_query());

while($row = mysql_fetch_array($result))
{
    echo $row['name'] . '<br>';
    echo $row['email'] . '<br>';
    echo $row['date'] . '<br>';
}

?>
Ands that is all there is to getting data out of mysql and displaying it.

#3 essjay_d12

essjay_d12
  • Members
  • PipPipPip
  • Advanced Member
  • 121 posts

Posted 14 March 2006 - 05:55 PM

Yes but there are 20 rows in the table all together and I only want 10, and i want all 20 to be ordered by date so the 10 i pull out are the latest ones.

#4 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 14 March 2006 - 06:01 PM

If you just want the first ten rows ordered by date then append your query with LIMIT 1, 10 like so:
$sql = "SELECT name, email, date From users ORDER BY date LIMIT 1, 10 ";
MySQL will query the database and order its results by the date and then it'll limit the already ordered rows by 10. So only 10 or less results (depending on how many rows there are in the database) should be returned.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users