Domanda

I am currently building a website where people can visit and enter a distance that they have run, swimmed, hiked or skiied. It's my first website and I didn't know anything about coding 2-3 months ago so have that in mind.

I have created a table where this is stored and also a leaderboard.php that fetches the data to a leaderboard.

This is how it looks right now:

Insert into table:

if (!mysqli_query($con,"INSERT INTO total(username, type, distance) VALUES ('$username', '$type', '$distance')"))

And to fetch the data into a leaderboard:

$result = mysqli_query($con, "SELECT username, distance FROM total ORDER BY distance DESC");
        $rank= 1;


if (mysqli_num_rows($result)) {
            while ($row = mysqli_fetch_assoc($result)) {
                 echo "<tr><td>{$rank}</td>
                      <td>{$row['username']}</td>
                      <td>{$row['distance']}</td></tr>";

            $rank++; 
        }
        }
    ?>  

The problem with this is that when someone enters their username/type/distance it creates new rows. So a person can have different ranks. I want the leaderboard to sum up all the distances from the different types of activities per user.

What is the proper coding for that? If possible I would like to only alter the leaderboard.php and not the table, cause I'm using that data for other parts of the site as well.

È stato utile?

Soluzione

Try this

SELECT username, sum(distance) as total_distance FROM total group by username ORDER BY total_distance desc;

Instead of

SELECT username, distance FROM total ORDER BY distance DESC;

and let me know if its working or not.

Altri suggerimenti

To clarify if someone else has a similar problem, or is interested in this.... I had to change some more so that the sum of the distances showed, and that it was sorted by the sum and not just the largest individual distance.

 $result = mysqli_query($con, "SELECT username, sum(distance), distance as total_distance FROM total group by username ORDER BY sum(distance) desc;");
    $rank= 1;

    if (mysqli_num_rows($result)) {
        while ($row = mysqli_fetch_assoc($result)) {
             echo "<tr><td>{$rank}</td>
                  <td>{$row['username']}</td>
                  <td>{$row['sum(distance)']}</td></tr>";

        $rank++;

        }
    }
?>

Thats my finished code^

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top