Php – thesql: Get row index count in thesql_fetch_assoc()


How can I get the row index count while looping in mysql_fetch_assoc()?

I dont want to use an external counter like this:

$counter= 0;

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

echo 'Row '.$counter;
$counter ++;


Is there any built in MySQL function to get the current row index in the loop?


The reason I don't want to use an external variable is that I switched from using one method to another to loop through a set of MySQL results.

I was using:

$result = mysql_query("SELECT * FROM table");
$num = mysql_num_rows($result);

for($x=0;$x < $num;$x++){

    echo 'Row '.$x;
    // $field = mysql_result($result,$x)


and now the MySQL_fetch_assoc() method above.

I mainly switched for keeping everyhing at it's simpliest. The for method make it pretty easy to keep track of the row index but the MySQL_fetch_assoc require the input of another variable.

Best Solution

Neither mysql DB nor mysqli driver has such a feature.

So, just use an "extrenal" counter - there is not a single problem with it.

Regarding switching methods, let me suggest you to switch to PDO. It would apparently fulfill your desire to simpler and cleaner code:

$stm = $pdo->prepare("SELECT * FROM table");
$data = $stm->fetchAll();
<? foreach ($data as $i => $row): ?>
      <a href="news.php?<?=$row['id']?>">
<? endforeach ?>