I've created a page which displays all the users on the site.
The user_id and the username is displayed for each user. I tried adding a follow button at the side of each user and in order to follow someone it grabs their user_id.
Unfortunately I can't get it to work because the user_id which is being grabbed is always the last one from the database, because of the loop.
So if you press the follow button for anyone on the list, it will always follow the last person.
How can I fix this?
I've been trying different methods for more than 20 hours but they all seem to have the same problem...
Here is the code:
<?php
class Database()
{
// connect
// query
public function fetchAll() {
$this->rows = $this->result->fetch_all(MYSQLI_ASSOC);
return $this->rows;
}
public function display() {
$this->query("SELECT * FROM `users`");
$this->fetchAll();
}
}
$class = new Database();
$users = $class->display();
foreach ($users as $user) {
$user_id = $user['user_id'];
$username = $user['username'];
echo $user_id . ' ' . $username;
echo '<form action="" method="post">';
echo '<input type="submit" name="follow" value="Follow">';
echo '</form>';
}
if ($_POST['follow']) {
$FClass->follow($user_id);
}
Yeah, that makes sense.
foreach ($users as $user) {
$user_id = $user['user_id']; // At the end of the loop this is the last user
$username = $user['username'];
echo $user_id . ' ' . $username;
echo '<form action="" method="post">';
echo '<input type="submit" name="follow" value="Follow">';
echo '</form>';
}
if ($_POST['follow']) {
// Regardless of what you input you're getting the last user here
$FClass->follow($user_id);
}
Try something like this
foreach ($users as $user) {
$user_id = $user['user_id']; // At the end of the loop this is the last user
$username = $user['username'];
echo $user_id . ' ' . $username;
echo '<form action="" method="post">';
echo '<input type="hidden" name="userid" value="' . $user_id . '">';
echo '<input type="submit" name="follow" value="' . $user_id . '">';
echo '</form>';
}
if ($_POST['follow']) {
// Regardless of what you input you're getting the last user here
error_log($_POST['follow']); // View your logs to verify
$FClass->follow($_POST['follow']);
// or
$FClass->follow($_POST['userid']);
}