I come with a problem with PHP and MYSQL. I tell you: I'm creating as a followers system, and I had it finished and I made it work, but the code was not the best we could say, because ... well, this was the code I had before:
$followers = "SELECT * FROM seguidores WHERE userSeguido = '".$userName."'";
$resultFollowers = $conexion->query($followers);
if ($resultFollowers->num_rows > 0) {
while ($dataFollowers = $resultFollowers->fetch_assoc()) {
$followedname = $dataFollowers['userSeguido'];
$followername = $dataFollowers['userSeguidor'];
$dataseguidores = "SELECT * FROM usuarios WHERE username = '".$followername."'";
$resultdataseguidores = $conexion->query($dataseguidores);
while ($dataFollowers_real = $resultdataseguidores->fetch_assoc()) {
$usernameSeg = $dataFollowers_real['username'];
$userprofilephotoSeg = $dataFollowers_real['userprofilephoto'];
echo "<a href=\"$completeURL/user/$usernameSeg/bio\">
<div class=\"follower\" style=\"background: url($completeURL/resize.php?r=$userprofilephotoSeg&w=200) center center / cover;\"></div>
</a>";
}
}
} else{
echo "<p class=\"no-follow\">$userName no tiene seguidores</p>";
}
It works, yes, but you see that piece of code, and I made another one that also works, but it duplicates the results.
Capture with the first code:
Capture with the second code:
And well, I do not know why it happens. I made the code wrong, but I forgot to tell you that I'm almost new to this from MYSQL and PHP.
I hope you can help me! If you need anything else, just tell me.
The code that does not work:
$seguidores = "SELECT * FROM
seguidores S
INNER JOIN
usuarios U ON S.userSeguido = '$userName'
WHERE U.username != '$userName'";
$result = $conexion->query($seguidores);
if ($result->num_rows > 0) {
while ($data = $result->fetch_assoc()) {
$seguidor_imagen = $data['userprofilephoto'];
$seguidor_nombre = $data['username'];
echo "<a href=\"$completeURL/user/$seguidor_nombre/bio\">
<div class=\"follower\" style=\"background: url($completeURL/resize.php?r=$seguidor_imagen&w=200) center center / cover;\"></div>
</a>";
}
} else{
echo "<p class=\"no-follow\">Nada por acá...</p>";
}
Structure of tables:
users:
- userID (PK user ID)
- username (username)
- userprofilephoto (User Profile Picture)
followers:
- IDuserfollow (user ID that was followed)
- IDuserseguidor (user ID that followed)
- userFollowed (Name of the user that was followed)
- userSeguidor (Username that followed)