0

I read somewhere (sorry I forgot where), that there is a way to associate an index number to rows fetched from an MySQL query result using a native PHP function (the person was not sure about the syntax so he didn't wrote it). For example:

The usual way:

$count = 1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    echo "<li> ". $count ."id: " . $row['id'] . " lon: " . $row['lon']. ", lat: ". $row['lat'].", ". $row['road']. " </li>";
    $count++;
}

I know that thinking of this other way is not that important, but I'm just curious if there really is a function for that purpose.

3
  • $row['id'], it's right there...Or do you just want to retrieve the id and not the rest? Or? Row count? row number? not clear to me, sorry.. Commented Feb 21, 2011 at 12:27
  • Doesn't the table you're fetching from has it's own primary key? Commented Feb 21, 2011 at 12:32
  • Were you thinking of mysql_num_rows (deprecated) to retrieve the count? Then loop over result using that? (not recommended) Commented May 7, 2019 at 11:07

1 Answer 1

3

you can add rownum to your results array, if you edit your sql like

SELECT @rownum:=@rownum+1 as rownum, p.* FROM MYTABLE p , (SELECT @rownum:=0) r 

so the loop like

    while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        echo "<li> ". $row['rownum'] ."id: " . $row['id'] . " lon: " . $row['lon']. ", 
        lat: ". $row['lat'].", ". $row['road']. " </li>";

    }
Sign up to request clarification or add additional context in comments.

1 Comment

So there is no native PHP-MySQL function for that. Thanks for the @rownum. I didn't know that.

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.