Norman
Norman

Reputation: 6365

Detect the end of a result set in php/mysql

How do you detect the last record in a result set when using php and mysql. In ASP its EOF (End of File). Whats the php/mysql equivalent? I'd like to know the last record so i can draw a line after it or close a tag or anything else.

Upvotes: 1

Views: 4953

Answers (1)

Emil Vikström
Emil Vikström

Reputation: 91983

You can use mysqli_num_rows to see how many rows there are in the result set and keep a counter to know how many rows you've printed.

$total_rows = mysqli_num_rows($resultset);
$counter = 0;
while($row = mysqli_fetch_assoc($resultset)) {
  //do something with every row here

  //last row?
  if(++$counter == $total_rows) {
    echo '<hr>';
  }
}

Or you can just loop through the rows and print your line/tag/whatever right after the loop:

while($row = mysqli_fetch_assoc($resultset)) {
  //do something with every row
}
echo '<hr>';

Upvotes: 9

Related Questions