-2

I have this code to get the list of users from the database and sort them by score.

$sql="SELECT * FROM users ORDER BY score DESC";
$result=mysql_query($sql);

while($rows=mysql_fetch_array($result)){

What I want to do, is to stop the loop proces, when the proces reach a decided username.

6 Answers6

1

Use break with if condition

while($rows=mysql_fetch_array($result)){
    if($rows['name'] == 'yourname') {
        break;
    }else {
        //your code
    }
}
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
1

You can do this

$sql="SELECT * FROM users ORDER BY score DESC";
$result=mysql_query($sql);

while($rows=mysql_fetch_array($result)){
  if($row['username']=='DecidedUser')
   break;
}
Mahendra
  • 908
  • 1
  • 18
  • 38
1

Use WHERE in mysql query like this.

$sql="SELECT * FROM users WHERE user_name='targetUserName' ORDER BY score DESC";
$result=mysql_query($sql);

Here user_name is mysql fieldname in users table.

Bharat Chodvadiya
  • 1,644
  • 4
  • 20
  • 31
0

use break;

$sql="SELECT * FROM users ORDER BY score DESC";
$result=mysql_query($sql);

while($rows=mysql_fetch_array($result)){
  if(Reached_at_user_name)
   break;
}
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86
0

break; is your friend

http://php.net/manual/en/control-structures.break.php

while($rows=mysql_fetch_array($result)){
    if (
        $row['username'] == 'username'
    ) {
        break;
    }
}

An alternative approach depending on your intention would be to just change the SQL query to do what you want instead, i.e. something like the following which uses the @includeThis variable to keep track of if it's hit the intended username yet

$sql="
    SELECT 
        u.*, 
        @includeThis AS includeThis,
        @includeThis := IF(u.username = 'TargetUserName',0,@includeThis) AS updateIncludeThis
    FROM users u, (SELECT @includeThis := 1) d 
    ORDER BY u.score DESC
    HAVING includeThis = 1
";

Additionally you shouldn't be using the mysql_ functions any more, and instead using mysqli_ or PDO. Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
0

inside your while you want to add something along the lines of.

if($rows['username'] == "targetUserName"){return;}

You could also use break; instead of return, however with return you can return true; to let your script know your function found the username, if required :)

Josh Undefined
  • 1,496
  • 5
  • 16
  • 27