如何根据另一个字符串的值获取表值?

时间:2013-08-20 08:58:47

标签: php mysql database

我不确定我是否使用了上面正确的行话,但我要做的是以下... 如何根据帖子的$ author_id匹配用户ID,让$ author输出用户名(来自mySQL用户tabel)?

<?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...";
}
?> 

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

mysql_query("SELECT posts.*, users.username FROM posts JOIN users ON author_id = users.id ORDER BY posts.id DESC LIMIT 20");

答案 2 :(得分:0)

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

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

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