aravk33
aravk33

Reputation: 489

php - How to find out the order no. of a row while displaying values?

I have code that takes values from a database that belong to a particular user.

<?php
$user = $_SESSION['username'];
$q = intval($_GET['q']);
$db = mysqli_connect('localhost', 'username', 'password', 'database_name');
$sql = "SELECT * FROM savedtimes WHERE username = '$user' AND session = '$q' ORDER BY timeid";
$result = mysqli_query($db, $sql);
//$SNo = I might need to put something over here which makes it show the order number.
echo "<table>
<tr>
<th>S.No.</th>
<th>time</th>
<th>Avg of 5</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $SNo . "</td>";//This is the S.no column.
    echo "<td>" . $row['value2'] . "</td>";
    echo "</tr>";
}
echo "</table>";
?>

Now, while it is displaying these values in the order of a field called timeid, which is on auto increment, I want to have a column called S.No (only while displaying, not in the actual database), which orders them from 1 to the last number. Please note that I can't just use 'timeid', because I have multiple users, so the numbers won't be continuous. So basically, the order is that of 'timeid', but I want a column showing up with continuous numbers. How do I do this?

Upvotes: 1

Views: 108

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Declare a counter variable (with a value of 1) outside of the while() loop. Display it inside the loop and subsequently increment it at the end of the loop.

// your code
$SNo = 1;
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $SNo . "</td>";
    echo "<td>" . $row['value2'] . "</td>";
    echo "</tr>";
    ++$SNo;
}
// your code

Upvotes: 3

Related Questions