【问题标题】:Users list, follow button not working properly用户列表,关注按钮无法正常工作
【发布时间】:2013-06-06 23:12:07
【问题描述】:

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

为每个用户显示 user_idusername。我尝试在每个用户的侧面添加一个 follow 按钮,以便 follow 抓住他们的 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);
 }

【问题讨论】:

    标签: php button twitter-follow


    【解决方案1】:

    是的,这是有道理的。

    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']);
    }
    

    【讨论】:

    • 在这种形式下,您实际上从未提交过用户名。您甚至可以使用隐藏字段。我会编辑以反映。
    • 谢谢你!现在可以了!我不太明白它是如何工作的,但确实如此。
    • 没问题。您从未在提交时将任何信息与您的表单一起发送,因此您从未将任何内容返回给您的 php 以供参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2018-02-07
    • 2015-01-31
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多