使用用户名从数据库获取所有结果

时间:2014-06-26 02:47:25

标签: php html mysql

如何使用PHP继续检查帖子?我有一段代码可以通过并获取所有帖子。当我echo $row['post_message'];时,我收到所有消息。当我将其设置为像$post = $row['post_message'];这样的变量时,并且<h2><?php echo $post;?></h2>我只得到一个结果。这是我的代码

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

所以,当我echo时,我得到I like pie I like pie 2alex likes food,当我将其存储在变量中时,我得到alex likes food。有任何想法吗?

1 个答案:

答案 0 :(得分:3)

您的问题出在while循环中。您将继续覆盖$post变量。它应该是:

$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $posts[] =  $row['post_message'];
}

应返回:

Array (
    [0] => I like pie I like pie 2,
    [1] => alex likes food
)

这允许你做这样的事情(作为例子):

foreach($posts as $post) {
    echo 'The user posted: ' . $post . '<br />';
}