PDO::FETCH_ASSOC 未获取所有内容

2021-12-26 00:00:00 function php mysql pdo

我有这个功能:

function get_following($user_id) {
 global $conn;
 $stmt = $conn->prepare("SELECT * FROM following WHERE `follower_id`=:user");
 $stmt->bindParam(':user', $user_id, PDO::PARAM_INT);
 $stmt->execute();
 $following =$stmt->fetch(PDO::FETCH_ASSOC);
 return $following;
}

以下表格如下所示:

|user_id|follower_id|
|   2   |     5     |
|   3   |     5     |
|   4   |     5     |

现在的问题是,当我实际调用该函数时,它只从表中选择一行,其中我的 follower_id = 5.

Now the problem is when I actually call the function it only selects one of the rows from the table, where my follower_id = 5.

推荐答案

$following 必须是一个行数组.您实际上只是在获取第一行.使用 PDOStatement::fetchAll() 获取它,如下所示:

$following will have to be an array of rows. You are actually only fetching the first row. Fetch it using PDOStatement::fetchAll(), like this:

$following = $stmt->fetchAll(PDO::FETCH_ASSOC);

相关文章