I have the following code:
/* Get the 10 latest posts from users you're following */
$stmt = $cxn->prepare('SELECT * FROM posts WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ?) ORDER BY datetime DESC LIMIT 15');
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
/* If a result exists, continue. */
if ($result->num_rows) {
while ($row = $result->fetch_assoc()) {
/* Get the user's username from their id */
$stmt = $cxn->prepare('SELECT username FROM users WHERE user_id = ?');
$stmt->bind_param('i', $row['user_id']);
$stmt->execute();
$stmt->bind_result($username);
$stmt->fetch();
$stmt->close(); // this is where I'm closing the connection
}
}
In the third last line, you'll notice that I'm closing the connection in the while loop. The issue is that, if I remove that line, I get the error on that line.
Fatal error: Call to a member function bind_param() on a non-object
I'm guessing that closing the connection and then re-opening it again for the next element in the loop is not a good thing. So, how can I fix this? Why do I get this error when I remove the close connection line?