0

我几乎有了这个,但无法弄清楚最后一步!从我匹配的两个表post_idusername,现在我只想使用下面的循环在帖子标题下打印用户名。查询生成下$joined表...但是如何将特定用户与帖子匹配?让我知道是否需要更多说明

function get_joined()
{
    $sql = "SELECT `posts`.`post_id` AS `post_id`, 
        `posts`.`post_date` AS `post_date`, 
        `posts`.`post_title` AS `post_title`, 
        `posts`.`post_body` AS `post_body`,
        `users`.`id` AS `user_id`, 
        `users`.`username` AS `user_name`
 FROM `posts`
LEFT JOIN `users` ON `users`.`id` = `posts`.`user_id`
ORDER BY `post_date` DESC"; 
$joined = mysql_query($sql);

return $joined;
}

打印帖子,我的问题是<?php echo $joined['username']; ?>

<?php

    $posts = get_posts();
    foreach($posts as $post)
    {
        ?>

    <h2><a href ="blog_read.php?pid=<?php echo $post['id']; ?>"><?php echo   $post['title']; ?></a></h2>
    <h4>By <font color="#FF6347"><?php echo $posts['user_name']; ?></a></font> on <?php echo $post['date']; ?></h4> 
    <h4><?php echo $post['total_comments']; ?> comments, last comment <?php echo $post['last_comment']; ?>
    <hr />

    <p><?php echo $post['preview']; ?>...</p>
    <?php

}

?>

用户表:
id|username
1 | steve
2 | jon
3 | mike

帖子表:
post_id|post_user|post_tite|post_body|post_date
1 | steve title body date
2 | steve title body date
3 | steve title body date

4

1 回答 1

2

您的get_posts函数应该将用户名加入到$posts中,可能是通过 SQLJOIN连接...否则,您的索引将不正确,并且您将在不属于那里的帖子上显示用户名(订单将是错误的)。

一个示例 SQL:

SELECT
  posts.id AS post_id,
  posts.date AS post_date,
  posts.title AS post_title,
  posts.content AS post_content,
  users.id AS user_id,
  users.username AS user_name
FROM
  posts
LEFT JOIN
  users ON users.id = posts.user_id
ORDER BY
  post_date DESC # newest first
于 2013-07-09T20:12:43.250 回答