0

I'm not to sure if I have used the correct jargon above but what I am trying to do is the follow... How do I get $author to output a users name (from the mySQL users tabel) on the basis that $author_id of the post, matches the users ID?

<?php 
include "inc/mysql-connect.php"; 
$DynamicFeed = "";
$sql = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 20");
$postCount = mysql_num_rows($sql); // count the output amount
if ($postCount > 0) {
  while($row = mysql_fetch_array($sql)){ 
    $id = $row["id"];
    $title = $row["title"];
    $post = $row["post"];
    $author_id = $row["author_id"];
    $author = $row["author_id"];
    $type = $row["type"];
    $date_posted = $row["date_posted"];
    $DynamicFeed .= "<div class=\"item\"><img class=\"img-type\" align=\"left\"       src=\"img/$type.jpg\"> <p><a href=\"droplet.php?id=$id\"><b>$title</b></a><br />by <a    href=\"profile.php?id=$author_id\">$author</a> on $date_posted<br /><br /> $post</p>    </div>";
}
} else {
$DynamicFeed = "It would appear that there ar'nt any Droplets here...";
}
?> 
4

3 回答 3

2

您可以使用 JOIN 语句,如下所示:

$sql = mysql_query("SELECT posts.*,users.name FROM posts LEFT JOIN users on posts.author_id=users.id ORDER BY posts.id DESC LIMIT 20");
于 2013-08-20T09:03:55.427 回答
1
mysql_query("SELECT posts.*, users.username FROM posts JOIN users ON author_id = users.id ORDER BY posts.id DESC LIMIT 20");
于 2013-08-20T09:03:05.787 回答
0

如果我理解正确,您应该通过加入用户表直接在查询中(而不是在循环中)执行此操作:

SELECT * FROM posts LEFT JOIN <user-table> ON <user-table>.id=author_id ORDER BY id DESC LIMIT 20"

然后你直接在 $row 数组中获取数据。如果两个表中的列名相同,则可能需要添加别名。

于 2013-08-20T09:06:46.663 回答