Wednesday 5 September 2018

Mysql LEFT JOIN does not work for 2 tables

Basically I have 2 tables

  • Topics
  • Users
I am trying to use a left join so that I can link the "posted_by" in "topics" with "user_id" in "users", so that I can output both the users.username for display, as well as users.profile(avatar picture).
Here is my current code, which is giving me boolean errors.
        <?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();
    ?>


I believe you are using something like
$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";

Try adding
$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, topics WHERE topics.posted_by = users.user_id ORDER BY topics.posted DESC";

0 comments:

Post a Comment