How to make this into a single query. I have formulated the following query:
$msgs=mysql_query("select m.subject, m.msg from message as m, message_users as mu where m.id=mu.msg_id and mu.user_id=$u_id order by dateof_msg desc");
while($row1=mysql_fetch_array($msgs))
{
$total_msg = $row1['msg'];
$own_id = mysql_query("select owner_id from message where msg='$total_msg' ");
while($o_id=mysql_fetch_array($own_id))
{
$owners_id = $o_id['owner_id'];
$uname = mysql_query("select name from users where id='$owners_id'");
while($username=mysql_fetch_array($uname))
{
$sen_name = $username['name'];
echo $sen_name." ".$owners_id." ".$total_msg."<br />";
}
}
}
because of the length of the query it runs really slow.
I edited the code now like this but it says mysql_fetch_array() excepts parameter 1 to be resource Boolean is given...
$userlist = mysql_query("select m.subject, m.msg, m.owner_id, u.name, u.id, mu.msg_id, mu.user_id from message as m, message_users as mu, users as u
m inner join u on (m.owner_id = u.id)
m inner join mu on(m.id=mu.msg_id) and
where mu.user_id='$u_id' order by dateof_msg desc") or mysql_error();
while($row=mysql_fetch_array($userlist))
{
$sendername = $row['name'];
echo $sendername;
}
Try this query:
select m.subject, m.msg, m.owner_id, users.name
from message as m, message_users as mu
inner join users on (message.owner_id = users.id)
where m.id=mu.msg_id and mu.user_id=$u_id order by dateof_msg desc
I could improve the answer if you explain me what do you want to do: What is the structure of message_users and message tables and why do you want to join both of them?
EDIT: What about this?
select m.id, m.subject, m.msg, owner.id,
owner.name, receivers.id, receivers.name
from message as m
inner join message_users as mu on (m.id = mu.msg_id)
inner join users as owner on (m.owner_id = owner.id)
inner join users as receivers on (m.user_id = receivers.id)
where receivers.user_id=$u_id
order by dateof_msg desc
The problem is that you'll get one row for each message and for each receiver, but with PHP you could group the information (is more efficient than 3 queries in a loop)