简体   繁体   中英

Query within a for each loop? Trying to get user name for each foreign ID number in each row returned

I am trying to display the user name of the person who liked another user's post for each record. I can only figure out how to display that user ID number so far though (which we get from points.LID). This is what code below does. I have tried a few things, but I can't figure out how to get a second sql query inside of the foreach loop so that I can get the user_name for the LID/ID for each liking user.

I need to get the user display name from LID sql somewhere/somehow so I can echo name of person who liked the post (the LID). I need use LID to connect to wp_users.ID in wp_users table and then grab wp_users.display_name. But can I insert such a query inside the foreach loop below?

I think I need to add something like (select points.LID from points where points.ID = $user_ID) Then get display name where wp_users.ID = points.LID

These are the 3 tables with the relevant columns: 1. points (ID, LID, SID), 2. stories (ID, story_name) 3. wp_users (ID, display_name)

//THIS CODE RETURNS name of story and the ID NUMBER of the person who liked it (LID). But I need it to return the user name of the person who liked it (wp_users.display_name)

//only need current user for ID of author
$user_ID = get_current_user_id()

$results = $dbh->prepare("select 
stories.ID,
stories.SID,
stories.story_name,
points.ID,
points.LID,
points.PID,
wp_users.ID,
wp_users.display_name
FROM stories
JOIN points ON stories.SID=points.SID
JOIN wp_users ON stories.ID=wp_users.ID
where (stories.ID = $user_ID) and (PID = 1)");
$results->execute();

$row = $results->fetchAll(PDO::FETCH_ASSOC);

if ($row) {
echo '<table>';
echo '<tr>';
echo '<td><b>Name</b></td>';
echo '<td><b>Author</b></td>';
echo '</tr>';
foreach ($row as $all) {

//Get user display name from LID sql here? So I can echo name of person
//who liked the post (the LID) below? I need use LID to connect to
//wp_users.ID in wp_users table and then grab wp_users.display_name

$stp = stripslashes($all['story_name']);
echo '<tr>';
echo "<td><a href=\"http://example.com/complete-text?
writing=$all[SID]\">$stp</a></td>";
echo "<td><a href=\"http://example.com/portfolio?ID=$all[LID]\">
$all['LID']</a></td>";
}
echo '</table>';
}
?>
SELECT 
  stories.ID,
  stories.SID,
  stories.story_name,
  points.ID,
  points.LID,
  points.PID,
  wp_users.ID,
  wp_users.display_name,
  wp_users2.display_name AS 'user_who_liked',
FROM
  stories 
  JOIN points 
    ON stories.SID = points.SID 
  JOIN wp_users 
    ON stories.ID = wp_users.ID 
  LEFT JOIN wp_users AS wp_users2 
    ON points.LID = wp_users2.ID 
WHERE (stories.ID = $user_ID) 
  AND (PID = 1) ;

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