Skip to content
Advertisement

How can I echo the position number of SQL row in PHP?

Before you misread the title… I’m not asking how to echo the number of rows, I’m simply looking to find the position that the row is in.

Let’s say we have five total rows:

+---------------------+
| Post ID | Author |
+---------------------+
|    463 | Me     |
|    477 | Me     |
|    718 | Me     |
|    883 | Me     |
|    276 | Me     |
+---------------------+

Now I’d like to get the position of the row that contains the post ID of 718. From looking at the data, we can visually see that it is the third row in the data. How can I echo this in PHP?

Advertisement

Answer

when you fetch records, you may use a variable as position number.

#DB is a class connect to mysql database.
DB::init();

$sql = "SELECT * FROM RowNo ";
$stmt = DB::query( $sql );

$i = 1;
while( $rec1 = $stmt->fetch() ) {
    echo "row $i : ";
    print_r( $rec1 );
    echo '<BR>'.PHP_EOL;
    $i++;
};

result :

row 1 : Array ( [Post ID] => 8788277463 [Author] => Me )
row 2 : Array ( [Post ID] => 2894728477 [Author] => Me )
row 3 : Array ( [Post ID] => 3898994718 [Author] => Me )
row 4 : Array ( [Post ID] => 4891784883 [Author] => Me )
row 5 : Array ( [Post ID] => 1185819276 [Author] => Me )
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement