I’ve started to code in April 2021 so I’m super new to this. Working on my final exam, I’d need your precious help! I want to generate a dynamic list from a database, containing 2 joined tables (users and interest). The 2 tables both contain "ID_user" which links them as a foreign key. The idea is that one the user is logged in, the profile page displays all the interests the user selected at sign up. At the moment I can only display the last interest selected and not all of them.
Here is my php:
$request2 = "SELECT `interest`.`name_Interest`
FROM `interest`
INNER JOIN `users`
ON `interest`.`ID_user` = `users`.`ID_user`
WHERE `pseudo` = '".$url_pseudo."'
";
$resultat2 = mysqli_query($connexion, $request2) or die (mysqli_error($connexion));
$nb_resultat2 = mysqli_num_rows($resultat2);
if ($nb_resultat2 > 0) {
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
}
Here is the HTML displaying the response:
Here is my db:
Any idea why I can get only 1 value?
thanks in advance
2
Answers
Your while loop is writing to the same variable for each iteration of the loop;
This will leave
$name_Interest
containing the last value from your database after the loop has completed.To resolve this, you will need to keep a list of interest names – this can be achieved by using an array. PHP Array Documentation
Now,
$interests
will hold all of the values from the database!You will need to print these out differently in your HTML, by looping through all the values in the array and printing one at a time:
(PHP foreach documentation)
Solution
Simple store all user interests on array and then show in iteration on page.
Code:
Now $user_interests array holds all interests of users as a result of join.
At last loop over it