简体   繁体   中英

How do I get a table value based on the value of another string?

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

您可以使用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");
mysql_query("SELECT posts.*, users.username FROM posts JOIN users ON author_id = users.id ORDER BY posts.id DESC LIMIT 20");

If I understand correctly, you should do this directly in your query (not in while cycle), by joining user table:

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

Then you get your data directly in $row array. You may need to add aliases, if you have same column names in both tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM