我创建了一个显示网站上所有用户的页面。
为每个用户显示 user_id 和用户名。我尝试在每个用户旁边添加关注按钮,然后关注某人抓住他们的 user_id 。
不幸的是我无法让它发挥作用,因为正在抓取的 user_id 始终是数据库中的最后一个,因为循环。
因此,如果您按下列表中任何人的关注按钮,它将始终关注 最后人。
我该如何解决这个问题?
我已经尝试了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);
}
答案 0 :(得分:0)
是的,这是有道理的。
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']);
}