1

我创建了一个页面,显示网站上的所有用户。

为每个用户显示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);
 }
4

1 回答 1

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']);
}
于 2013-06-06T23:23:23.687 回答