如何使用 PHP 从多个表中选择数据并显示它?
我正在尝试制作一个私人消息应用程序.我需要收件箱同时显示主要消息"和消息答复".
I'm trying to make a Private Message Application. And I need the Inbox to show both "main messages" and "answers on messages".
我的表如下:
发布
id - 标题 - 内容 - from_user - to_user -receiver_opened - user_bywho - 时间戳.
id - header - content - from_user - to_user - receiver_opened - user_bywho - timestamp.
post_answer
id - answer_from_user - answer_to_user - answer_user_bywho - answer_header - answer_content - answer_id - timestamp_svar.
id - answer_from_user - answer_to_user - answer_user_bywho - answer_header - answer_content - answer_id - timestamp_svar.
现在我遇到了麻烦.因为我不知道如何使这成为可能.
And now I'm having troubles. Because I don't know how to make this possible.
我的 mysql_query 现在看起来像这样:
My mysql_query looks like this right now:
$user = $_SESSION['username'];
$sql = mysql_query("SELECT * FROM post,post_answer WHERE ".
"answer_to_user='$user' AND to_user='$user'")
or die(mysql_error());
提前致谢.
该查询无效,因为它对于 id
字段会产生歧义.
The query is not valid as it will be ambiguous about the id
field.
为此,您可以使用 JOIN
SELECT *
FROM post
INNER JOIN post_answer
WHERE post.to_user = post_answer.answer_to_user
愚蠢的方式(易于理解)
SELECT post.id,
header,
content,
from_user,
to_user,
receiver_opened,
user_bywho, timestamp,
post_content.id,
answer_from_user,
answer_to_user,
answer_user_bywho,
answer_header,
answer_content,
answer_id,
timestamp_svar
FROM post,
post_content
WHERE answer_to_user=$user AND
to_user=$user
希望能帮到你
假设您的表格包含以下字段:
Lets suppose your table contains fields like-
- 名字
- 姓氏
- 数量
看看你是否在数组中得到结果,比如 $results
.
See if you get the result in an array say $results
.
foreach ($results as $result)
{
echo $result->firstname;
echo $result->lastname;
echo $result->number;
}