This code works to give me what I want in my phpMyAdmin server:
SET @row_number = 0;
SELECT salesperson, units, profit, (@row_number:=@row_number + 1) AS position
FROM sales AS t ORDER BY profit DESC;
The problem happens when I transfer this to php:
<?php
$sql = "SELECT salesperson, units, profit, (@row_number:=@row_number + 1) AS positionn"
. "FROM sales AS t ORDER BY profit DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result))
echo $row['salesperson'] . " " . $row['units'] . " " . $row['profit'] .$row['position'] . "<br>";
}
It outputs the first three rows but not the fourth. The alias created with SQL.
2
Answers
First of all, you choose not exactly the best way to debug your output. Stringifying
$row['position']
directly (by piping it intoecho
) hides a lot of useful info that you would be able to find otherwise.Second, the query in your second snippet misses actually setting up that variable, like this:
Additionally, in the latest version of MySQL (8.0+) window functions are finally supported which avoids the use of
@
session variables. Doing so you can also add row numbers by group withPARTITION BY
clause: