如何使用 PHP 从多个表中选择数据并显示它? [英] How do I SELECT data from more than one table and display it, with PHP ?

查看:37
本文介绍了如何使用 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-

  1. 名字
  2. 姓氏
  3. 数量

看看你是否在数组中得到结果,比如 $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;
}

这篇关于如何使用 PHP 从多个表中选择数据并显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆