Please clarify, I myself can not understand at all. There are 2 tables, posts and user. posts has columns id text author, and user has id names. The author column is associated with the user table. When outputting data from posts in a loop, we get the user id, but how do you print name instead of id?

$res = mysqli_query($link,"SELECT * FROM post "); $rows[] = mysqli_fetch_assoc($res); foreach ($rows as $row){ ?> <span><? echo $row['text'] ?></span><br> <span><? echo $row['author_id'] ?></span> <? } 
  • Give an example of a request or code - JVic
  • I hope in the author idishnik? - Kirill Korushkin
  • @KirillKorushkin yes - Senbonzakuraa
  • @JVic edited - Senbonzakuraa

2 answers 2

  $result = mysqli_query($link," SELECT user.name, post.text FROM post INNER JOIN user ON post.author = user.id "); $str = ''; while ($row = mysqli_fetch_assoc($result)) { $str .= '<span>' . $row['text'] . '</span><br>'; $str .= '<span>' . $row['name'] . '</span><br>'; } echo $str; 

You cannot generate an output string and output at the same time; you should always try to separate these parts.

This mysqli_fetch_assoc function was used incorrectly , as it returns only one record per query result.

  • I don’t really understand the meaning of declaring the $ str variable before the loop. You also forgot to put $ in the last line) - Senbonzakuraa
  • Because it is necessary to separate the logic of formation of the output and the conclusion itself. The conclusion should be one, in one place. And you have everything a little and everything on the heap, a very bad style. You can look at MVC in php, there will be even more clear why so divided. Yes, I forgot, thank you) - Mykola Veriga
 SELECT p.id, p.text, u.name FROM posts p JOIN user u ON p.author = u.id