简体   繁体   中英

MYSQL retrieve data from two tables

I am trying to make a small discussion system where people can login and post a discussion. On the homepage I want to show the discussions.

First I retrieve the data for the discussions (topic, category, username, etc) from the table 'discussions'and order them by 'date_time'.

I put these values in div's that are working just how I want it. The problem I am having now is to show the avatar of the user. The avatars are stored in a table 'users' under the column 'avatar'.

So I need to retrieve the value from the column 'avatar' in the table 'users' where 'username' matches the username of the discussion.

This is the code that I have now but it's not working. I have tried different things but I am not very familiar yet with PHP so I don't really know how to go from here.

Thanks in advance!

$result = mysql_query("SELECT 
        topic, 
        category, 
        date_time, 
        username, 
        SUBSTRING(discussion, 1, 80) AS discussion 
    FROM discussions 
    ORDER BY date_time DESC");  
while($record = mysql_fetch_array($result))
{
?>
<div class="discusscolumn">
    <div>
        <p><? echo $record['category'] . ":  <b>" . $record['topic'] . "</b>"?></p>
    </div>
    <div>
    <?php
        $discussion_username=$record['username'];
        $getavatar = mysql_query("SELECT avatar, username FROM users WHERE username='$discussion_username' ");
        $avatarrecord = mysql_fetch_array($getavatar);
        echo'<span class="smallpic"><img src="user/'.$record['username'].'/'.$getavatar['avatar'].'"></span>'; 
    ?>
    </div>
    <div>
        <p>Posted by <? echo "<a href='user.php?u=".$record['username']."'>".$record['username'] ?> </a></p>
    </div>
    <div>
        <p><br><? echo $record['discussion'] ?>&nbsp...</p>
    </div>
    <div>
        <p><? echo $record['date_time'] ?></p>
    </div>
    <div><a href="#">Discuss</a></div>
</div>
<?php } ?>

PS: I know I am working with mysql instead of mysqli and that I'm mixing HTML and PHP code but I just want the basics to work now.

Please check your img source(src) , that you have passed as user/username/avatar instead of passing like this please put url like http://www.w3schools.com/images/w3schools_green.jpg so that you will be getting out . But in your case you need to have all your user image in some other global storage area for eg.Amazon s3 bucket , and you need to get string from database construct like above url and append that in img src inside input tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM