我创建了一个显示网站上所有用户的页面。
显示每个用户的user_id和username。我试着在每个用户的侧面添加一个跟随按钮,为了跟随某人,它抓住了他们的user_id。
不幸的是,我不能让它工作,因为被抓取的user_id总是最后一个从数据库,因为循环。
因此,如果您为列表中的任何人按follow按钮,它将始终跟随最后一个人。
我该如何解决这个问题?
我已经尝试了20多个小时的不同方法,但他们似乎都有同样的问题…
代码如下:
<?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);
}
是啊,有道理。
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);
}
试试这样
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']);
}