0

基本上我有2张桌子

  • 话题
  • 用户

我正在尝试使用左连接,以便我可以将“主题”中的“posted_by”与“用户”中的“user_id”链接起来,这样我就可以输出 users.username 以供显示,以及 users.profile(头像图片)。

这是我当前的代码,它给了我布尔错误。

        <?php
    include 'core/init.php';
    include 'includes/overall/header.php';

    $sql = " SELECT *, users.id, users.username, users.profile
        FROM `topics` 
        LEFT JOIN
        users ON topics.posted_by = " . mysql_real_escape_string($_GET['topic_id']) . " users.user_id ORDER BY `posted` DESC";

    $result = mysql_query($sql);

    // Start looping table row
    while($rows = mysql_fetch_array($result)){
    ?>
    <table>
      <tr> 
        <td rowspan="4"> Avatar code to go here<br>
           <? echo $rows['username']; ?></td>
        <td><? echo $rows['category']; ?> > <? echo $rows['sub_category']; ?> </td>
      </tr>
      <tr>
        <td><? echo $rows['posted']; ?></td>
      </tr>
      <tr>
        <td><? echo $rows['topic_data']; ?></td>
      </tr>
      <tr>
        <td><a href="view_topic.php?id=<? echo $rows['topic_id']; ?>">Reply</a> (<? echo $rows['reply']; ?>) Replies</td>
      </tr>
    </table>

    <?php
    // Exit looping and close connection 
    }
    mysql_close();
    ?>
4

3 回答 3

0

ON topics.posted_by = " . mysql_real_escape_string($_GET['topic_id']) . " users.user_id你知道这会产生ON topics.posted_by = 1 users.user_id例如无效的 SQL 语法。改用 WHERE

ON topics.posted_by = users.user_id WHERE topics.id = (topic_id_variable)

PS:mysql_强烈不推荐使用。您应该更改 API。

于 2013-07-11T13:58:08.723 回答
0

您需要在您的连接子句中提供users关联方式。topics您已经为您的连接子句提供了一个外部变量。这不允许数据库引擎建立关于如何连接两个表的关系。

我相信您期望的查询应该是这样的

$sql = " SELECT *, users.id, users.username, users.profile
        FROM `topics` 
        LEFT JOIN
        users ON topics.posted_by = users.user_id 
        WHERE topics.id = '" . mysql_real_escape_string($_GET['topic_id']) . "'
        ORDER BY `posted` DESC";
于 2013-07-11T13:58:23.513 回答
0

我相信你正在使用类似的东西

$sql = "SELECT users.user_id, users.username, users.profile, topics.topic_id,     topics.category, topics.sub_category, 
topics.topic_data, topics.posted_by, topics.posted, topics.view, topics.reply 
FROM users WHERE topics.posted_by = users.user_id ORDER BY topics.posted DESC";

尝试添加

$sql = "选择 users.user_id、users.username、users.profile、topics.topic_id、topics.category、topics.sub_category、topics.topic_data、topics.posted_by、topics.posted、topics.view、topics.reply FROM users , 主题WHERE topic.posted_by = users.user_id ORDER BY topics.posted DESC";

于 2013-07-11T14:45:32.867 回答