PHP MySQL从连接表打印用户字段

时间:2013-07-09 20:07:33

标签: php mysql sql

我几乎有这个,但无法弄清楚最后一步!我从两个表中将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

1 个答案:

答案 0 :(得分:2)

您的get_posts函数应该将用户名加入$posts,可能是通过SQL JOIN加入...否则,您的索引将不正确并且您将显示用户名不属于那里的帖子(订单会出错)。

示例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