Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php sql linking together primary and foreign keys (linked lists)

So here's the desired thing i'd like to do. I have two tables in sql I'd like to echo out all the messages and the username of the message sender.

here's how the tables are set up.

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

desired output would be like this

new abc

new jkl

bob cbd

My code so far only outputs the messages

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

while($row = mysql_fetch_array($result))
  {
  echo  $row['msg']  ;
  }
like image 387
ramr Avatar asked Jan 21 '13 11:01

ramr


2 Answers

Try this query to obtain the user_name

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']  ;
}
like image 54
Igor Avatar answered Nov 18 '22 21:11

Igor


$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'];
  }

This should work.

Please comment if it doesnt

like image 29
CoBolt Avatar answered Nov 18 '22 21:11

CoBolt