Reputation:
How can I keep checking for posts with PHP? I have a piece of code that goes through and gets all the posts. When I do echo $row['post_message'];
I get all of the messages. When I set it as a variable like this $post = $row['post_message'];
, and do <h2><?php echo $post;?></h2>
I only get one result. Here's my code
$stmt = $con->prepare("SELECT post_message FROM posts WHERE post_user = :username");
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$row = $stmt->fetchAll();
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$post = $row['post_message'];
}
So when I do echo
I get I like pie I like pie 2alex likes food
, and when I store it in a variable I get alex likes food
. Any ideas?
Upvotes: 1
Views: 75
Reputation: 13128
Your issue lies in your while
loop. You keep overwriting the $post
variable. It should be:
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = $row['post_message'];
}
Which should return:
Array (
[0] => I like pie I like pie 2,
[1] => alex likes food
)
This allows you to do something like this (as an example):
foreach($posts as $post) {
echo 'The user posted: ' . $post . '<br />';
}
Upvotes: 3