Search code examples
phpranking

PHP loop outputting duplicates


public function select(){
    $rows = [];
    $connection = $this->connect();
    $result = $connection->query("SELECT username FROM users");
    while ($row = $result->fetch_assoc()){
        $rows[] = $row;
    }

    $userlist = 0;
    foreach($rows as $username){
        $userlist .= $username['username'];
    }

    $get_rankings = [1,2,3,4];
    $get_image_path = "images/";
    $total = 0;

    for ($x = 0; $x < count($get_rankings); $x++){
        $total = $get_rankings[$x];
        $path .=  "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
        // echo "<span  class = 'align-down'>{$path}";
        // echo "<p class = 'user-name'> {$rows['0']}</p>";
        // echo "</span>";
    }

    echo $path;
}

I'm trying to output a simple ranking but using the number index as images to display them.

In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.

The output im getting is this:

enter image description here

It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly

The desired output is:

enter image description here

My DataBase reads as:

[id][username][password]

If there is an easier solution, i'm all ears. I don't know how to approach this.


Solution

  • There's no need for $userlist. Output the username from $rows[$x].

    $path = "";
    $max = min(count($rows), count($get_rankings));
    for ($x = 0; $x < $max; $x++){
        $total = $get_rankings[$x];
        $path .=  "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
        // echo "<span  class = 'align-down'>{$path}";
        // echo "<p class = 'user-name'> {$rows['0']}</p>";
        // echo "</span>";
    }