Page 1 of 1

Loop x number of times

Posted: Thu Sep 16, 2010 3:56 am
by tonchily
Okay, so how do I loop something (eg get top10 id's from db ordered by ascending) for lets say 10 times?

Re: Loop x number of times

Posted: Thu Sep 16, 2010 4:04 am
by requinix
Two separate questions, two separate answers.
tonchily wrote:get top10 id's from db ordered by ascending
Use the appropriate SQL query.
tonchily wrote:Okay, so how do I loop something...for lets say 10 times?
Use a for loop.

Re: Loop x number of times

Posted: Thu Sep 16, 2010 4:08 am
by tonchily
tasairis wrote: Use a for loop.
Is there any other way? I can't get to figure out how for loop works.

Re: Loop x number of times

Posted: Thu Sep 16, 2010 11:26 am
by greyhoundcode
There are various forms of looping that you might use in addition to for loops, such as a while loop or do while, they are worth reading up on.

Regarding a for loop:

Code: Select all

for ($i = 0; $i <= 10; $i++)
{
    // Do stuff in here
    echo "$i <br/>";
}
The first thing to notice is $i = 0, this sets the variable $i to zero. Then we have the condition $i <= 10 which means the stuff inside the for loop will keep running so long as $i does not exceed 10. Finally $i++ increments the value of $i by one, which will happen at the end of each cycle through the loop.

Don't know if that helps you at all, but you never know...

Re: Loop x number of times

Posted: Thu Sep 16, 2010 4:59 pm
by tonchily
greyhoundcode wrote:There are various forms of looping that you might use in addition to for loops, such as a while loop or do while, they are worth reading up on.

Regarding a for loop:

Code: Select all

for ($i = 0; $i <= 10; $i++)
{
    // Do stuff in here
    echo "$i <br/>";
}
The first thing to notice is $i = 0, this sets the variable $i to zero. Then we have the condition $i <= 10 which means the stuff inside the for loop will keep running so long as $i does not exceed 10. Finally $i++ increments the value of $i by one, which will happen at the end of each cycle through the loop.

Don't know if that helps you at all, but you never know...
Yeah, thanks. Think it just helped.
The first I do is run a query where it sorts users by their points descending. After that, my $i variable was actually my id variable, so it "fetched" (dunno if it's the right word) the top10 ones. Thanks for help.

Re: Loop x number of times

Posted: Thu Sep 16, 2010 5:06 pm
by McInfo
tonchily wrote:how do I [...] get top10 id's from db
You shouldn't use a loop for this. (Which is why tasairis said your question was actually two questions.)

Use a query with a LIMIT clause.

Code: Select all

SELECT id FROM table_name ORDER BY id LIMIT 10; # The first 10 results (0-9)
SELECT id FROM table_name ORDER BY id LIMIT 0, 10; # Also the first 10 results (0-9)
SELECT id FROM table_name ORDER BY id LIMIT 10, 10; # The next 10 results (10-19)
# This is a comment