I am doing a medal system and when I try to list the medals it shows me only one. In this case, the test user has two medals.
This is the script
<?php
$user = $conn->query("SELECT * FROM usuario INNER JOIN medallas ON usuario.idu = medallas.idus WHERE idu = '".$userid."'");
$row = $user->fetch();
?>
<h1>Hola <?=$row['nombre'];?></h1>
Tus medallas
<?php
while ($rows = $user->fetch()) {
?>
<img src="<?=$rows['medalla'];?>" width="48"><br>
<?php
}
?>
The problem is that you have two
fetch
.It is necessary to understand that it
query
returns a pointer and each time you applyfetch
the pointer it moves one row , so when you apply the secondfetch
the pointer is already in the 2nd row of data.A non-optimal solution would be this:
The solution is not optimal because in your query the username is repeated over and over again, you should implement a grouping query, to fetch the username only once and his list of medals.
I have written a clearer code, avoiding so many block openings and closings.
The problem is that you use
fetch()
before that'swhile
why you only get a medal. Try like this: