0

I have a simple while loop like this

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

}

It fetches many rows one by one and it is fine. But i have add some extra features according to the row number.

  • when row number=1( first row)-do something
  • when row number=2( second row)-do something new

how can i get that ROW NUMBER of the each row?

1
  • 1
    Why not just count it in PHP? Commented Nov 29, 2013 at 3:46

3 Answers 3

2

Add a count variable:

$count = 1;
while ( $row = mysql_fetch_array( $result ) ) {
    // do your work here
    $count++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You will have to include the row number in your select SQL. So updated your MySQL SQL Statement that fetches the rows, to include the row number as follows.

select @rownum:=@rownum+1 ‘row_number’, * from your_table, (SELECT @rownum:=0) r 

This will create a variable rownum, initialize with value 0 & increase it by 1 for every record. Each row will have a column called row_number with ascending number starting from 1.

Then in your while... loop check for this row_number value and do processing accordingly.

Reference: See this post for another approach that involves creating a separate variable in SQL statement.

Comments

0

add an extra field in the select called row like this

SELECT @row:=IFNULL(@row,0)+1 as row,
       your_columns
  FROM your_tables

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.