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

问题描述:

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

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

因此,当我执行echo时,我会得到I like pie I like pie 2alex likes food,而将其存储在变量中时,则会得到alex likes food.有任何想法吗?

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?

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

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

应该返回:

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


这使您可以执行以下操作(例如 ):

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