Php sql binding primary and foreign keys (linked lists)

So, here is the desired thing that I would like to do. I have two tables in sql. I would like to track all messages and the username of the sender of the message.

here how tables are configured.

table name: user   
user_id user_name
   1       abc
   2       bob  
   3       pqr


table2 name : message
intro_id       user_id        msg
    1              4          abc
    2              4          jkl 
    3              2          cbd

the desired result will be as

new abc

new jkl

bob cbd

My code so far only displays messages

$result = mysql_query("SELECT * FROM message");

while($row = mysql_fetch_array($result))
  {
  echo  $row['msg']  ;
  }
+5
source share
2 answers

Try this query to get username

mysql_query("SELECT user.user_name, message.msg FROM message INNER JOIN user ON message.user_id = user.user_id");
while($row = mysql_fetch_array($result))
{
   echo  $row['user_name'] . ": " . $row['msg']  ;
}
+4
source
$result = mysql_query("SELECT user.user_name,message.msg FROM user,message WHERE user.user_id=message.user_id");

while($row = mysql_fetch_array($result))
  {
  echo  $row['user_name']." ".$row['msg'];
  }

That should work.

Comment if it is not

+4
source

All Articles