tags:

views:

55

answers:

2

Hi folks,

I would appreciate some help on this, I have a result set which I am trying to work with. The result contains 2 fields and any number of rows.

In calling fetch_row() how can you tell if the method has got to the last row?

I am iterating through the rows using:

while(list($className, $classID) = $result->fetch_row()) { 

  echo "<tr><td>$className has ID $classID.</td></tr>"

// Here, if the loop is for the last time I need to allow some extra code to run
// echo "<tr><td>Last Item.</td></tr>"

}

I was thinking about having an incremental counter in the while loop which compares the row to num_rows but was thinking that there must be a slicker was of telling if you have reached the last row

Any advice much appreciated. Many Thanks ShaunMc

+2  A: 

I was thinking about having an incremental counter in the while loop which compares the row to num_rows but was thinking that there must be a slicker was of telling if you have reached the last row

Nope, I think that is actually the only way to do this, regardless of which DB wrapper you're using (I assume it's PDO.)

It's a shame really: PHP should have something like this built in, at least in foreach constructs. But it doesn't.

Pekka
Its most likey Mysqli, PDO uses CamelCase method names.
prodigitalson
@Col I don't mean for `fetch_row` to return that, but it would be nice if `foreach` had a built-in `first_row` / `last_row` indicator.
Pekka
A: 

fetch_row() returns null when it hits the end of the result set.

http://php.net/manual/en/mysqli-result.fetch-row.php

Or am I missing something.

Jaydee
He probably wants to do somethig conditionally within the loop structure when hes dealing with the last result, not after... if he calls fetch_row inside and it isnt the last result then hes moved the result set forward an iteration thus skipping all preceeding logic within the loop for that result. he could always seek back but that would still require knowing what result index hes at.
prodigitalson
Jaydee