Search code examples
sqlmysql-num-rows

Adding Row Number on SQL SELECT


Okay this is going be probably very simple, but I've spent 4 hours on this and I'm giving up to ask what I'm missing. I am doing an SQL SELECT statement:

"SELECT username, id, Days FROM Users ORDER BY Days DESC";

Very simple. But now, when displaying all of my data using this:

if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>Days</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . **$row["id"].** "</td><td>" . $row["username"]. "</td><td>" . $row["Days"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

I would like the first one replacing the bold $row['id'] to be the row number.

I have tried all of the following:

SELECT *, number = ROW_NUMBER() OVER (ORDER BY Days) FROM Users AS rownumber ORDER BY Days;


SELECT ROW_NUMBER() OVER (Order by Days) AS 'RowNumber', username FROM Users

SELECT  username, Days, id, ROW_NUMBER() OVER(ORDER BY Days) AS 'RowNumber' FROM Users";

^^ all of which were things I found on internet. None have worked. Am I missing something blindly obvious here?


Solution

  • If you are using a programming language, you can keep your SQL simple:

    "SELECT username, id, Days FROM Users ORDER BY Days DESC";
    

    Then process the row number using the programming language:

    if ($result->num_rows > 0) {
    $rowNumber=0;
    echo "<table><tr><th>ID</th><th>Name</th><th>Days</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $rowNumber++;
        echo "<tr><td>" . $rowNumber "</td><td>" . $row["username"]. "</td><td>" . $row["Days"]. "</td></tr>";
    }
    echo "</table>";
    } else {
    echo "0 results";
    }