Q:

Display data from two sql tables using PHP mySQL

I made this Social Networking website http://friendquest.rf.gd. I have a problem in the news feed which am unable to figure this out. So everything works but not the way I want! I made an SQL Table called posts and reposts, where posts is the data a user enters to show in the news feed in my website, and repost works like a share button or retweet button from twitter.
Now I want the two tables to be displayed simultaneously.
For example, I posted a post that becomes id 31. Now a friend of mine reposts id 31, sorted according to time it should display like this - 
Repost id 3 for Post id 31

Post id 33

Post id 32

Post id 31
How my code displays the data when a repost is done -
Post id 33

Post id 32

Repost id 31 for post id 31

Post id 31
I can't figure out how to get the reposts at the top according to the time posted.. Here is my code for reposts
public function getRepostsPosts($post_id, $first_name, $last_name, $body, $imageDiv, $orig_poster, $imagePath){
    $query = mysqli_query($this->con, "SELECT * FROM reposts WHERE post_id='$post_id'");
    $html = "";

    if(mysqli_num_rows($query) > 0){
        while($row = mysqli_fetch_array($query)){
            $repost_body = $row['body'];
            $repost_by = $row['repost_by'];
            $users_query = mysqli_query($this->con, "SELECT * FROM users WHERE username='$repost_by'");
            $users_row = mysqli_fetch_array($users_query);
            $reposted_first_name = $users_row['first_name'];
            $reposted_last_name = $users_row['last_name'];
            $num = mysqli_num_rows($query);

            if($this->user_obj->isFriend($repost_by)){
                $link = "<a href='$repost_by'> $reposted_first_name $reposted_last_name </a>";
            }

            else{
                $link = "$reposted_first_name $reposted_last_name";
            }

            if($repost_body != ""){
                $body_html = "<br>
                                <p>And said \"$repost_body\".</p>
                            <br>";
            }

            else{
                $body_html = "";
            }

            $html .= "<div class='status_post'>
                        <div class='reposted_by' style='color:#ACACAC;'>
                            $link Reposted <a href='$orig_poster'>$first_name $last_name</a>'s <a href='post.php?id=$post_id'>Post</a>
                            $body_html
                            <div id='repost_body' onclick='location.href = \"post.php?id=$post_id\"'>
                                $body
                                <br>
                                $imageDiv
                                <br>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div id='myModal$post_id' class='imageModal' style='display: none'>
                        <div class='modalContent'>
                            <img src='$imagePath' class='modalImage'>
                            <br>
                            <button class='button cursor' onclick='closeModal$post_id()'>Close</button>
                        </div>
                    </div>
                    <br>";

                    //return $html;

        }
        return $html;
    }

    else{
        return "";
    }
}

And here is my code for the Posts
public function loadPostsFriends($data, $limit) {

    $page = $data['page']; 
    $userLoggedIn = $this->user_obj->getUsername();

    if($page == 1) 
        $start = 0;
    else 
        $start = ($page - 1) * $limit;

    $str = ""; //String to return 
    $data_query = mysqli_query($this->con, "SELECT * FROM posts WHERE deleted='no' ORDER BY id DESC");

    if(mysqli_num_rows($data_query) > 0) {

        $num_iterations = 0; //Number of results checked (not necasserily posted)
        $count = 1;

        while($row = mysqli_fetch_array($data_query)) {

            $id = $row['id'];
            $body = $row['body'];
            $added_by = $row['added_by'];
            $date_time = $row['date_added'];
            $imagePath = $row['image'];

            //Prepare user_to string so it can be included even if not posted to a user
            if($row['user_to'] == "none") {
                $user_to = "";
            }
            else {
                $user_to_obj = new User($this->con, $row['user_to']);
                $user_to_name = $user_to_obj->getFirstAndLastName();
                $user_to = "to <a href='" . $row['user_to'] ."'>" . $user_to_name . "</a>";
            }

            //Check if user who posted, has their account closed
            $added_by_obj = new User($this->con, $added_by);
            if($added_by_obj->isClosed()) {
                continue;
            }

            $user_logged_obj = new User($this->con, $userLoggedIn);

            if($user_logged_obj->isFriend($added_by)){              

                if($num_iterations++ < $start)
                    continue; 

                //Once 10 posts have been loaded, break
                if($count > $limit) {
                    break;
                }
                else {
                    $count++;
                }

                if($userLoggedIn == $added_by){
                    $delete_button = "<button class='delete_button' id='post$id' data-toggle='modal' data-target='#delete_form$id'>Delete Post</button>";
                    $edit_button = "<button class='edit_button' id='post$id' data-toggle='modal' data-target='#edit_form$id'>Edit Post</button>";
                    $repost_button = "";
                }

                else{
                    $delete_button = "";
                    $edit_button = "";
                    $repost_button = "<button class='edit_button' id='post$id' data-toggle='modal' data-target='#repost_form$id'><img src='assets/images/icons/repost.png' class='repostButton'>Repost</button>";
                }

                $user_details_query = mysqli_query($this->con, "SELECT first_name, last_name, profile_pic FROM users WHERE username='$added_by'");
                $user_row = mysqli_fetch_array($user_details_query);
                $first_name = $user_row['first_name'];
                $last_name = $user_row['last_name'];
                $profile_pic = $user_row['profile_pic'];

                ?>

                <script>

                    function openModal<?php echo $id?>(){
                        document.getElementById('myModal<?php echo $id ?>').style.display = "block";
                    }

                    function closeModal<?php echo $id?>(){
                        document.getElementById('myModal<?php echo $id ?>').style.display = "none";
                    }

                    function toggle<?php echo $id; ?>(){

                        var target = $(event.target);
                        if(!target.is("a") && !target.is("button") && !target.is("img") && !target.is("textarea") && !target.is("")){

                            var element = document.getElementById("toggleComment<?php echo $id; ?>");
                            if(element.style.display == "block"){
                                element.style.display = "none";
                            }
                            else{
                                element.style.display = "block";
                            }

                        }

                    }

                </script>

                <?php

                $comments_check = mysqli_query($this->con, "SELECT * FROM comments WHERE post_id='$id'");
                $comments_check_num = mysqli_num_rows($comments_check);

                //Timeframe
                $date_time_now = date("Y-m-d H:i:s");
                $start_date = new DateTime($date_time); //Time of post
                $end_date = new DateTime($date_time_now); //Current time
                $interval = $start_date->diff($end_date); //Difference between dates 
                if($interval->y >= 1) {
                    if($interval == 1)
                        $time_message = $interval->y . " year ago"; //1 year ago
                    else 
                        $time_message = $interval->y . " years ago"; //1+ year ago
                }
                else if ($interval-> m >= 1) {
                    if($interval->d == 0) {
                        $days = " ago";
                    }
                    else if($interval->d == 1) {
                        $days = $interval->d . " day ago";
                    }
                    else {
                        $days = $interval->d . " days ago";
                    }

                    if($interval->m == 1) {
                        $time_message = $interval->m . " month". $days;
                    }
                    else {
                        $time_message = $interval->m . " months". $days;
                    }

                }
                else if($interval->d >= 1) {
                    if($interval->d == 1) {
                        $time_message = "Yesterday";
                    }
                    else {
                        $time_message = $interval->d . " days ago";
                    }
                }
                else if($interval->h >= 1) {
                    if($interval->h == 1) {
                        $time_message = $interval->h . " hour ago";
                    }
                    else {
                        $time_message = $interval->h . " hours ago";
                    }
                }
                else if($interval->i >= 1) {
                    if($interval->i == 1) {
                        $time_message = $interval->i . " minute ago";
                    }
                    else {
                        $time_message = $interval->i . " minutes ago";
                    }
                }
                else {
                    if($interval->s < 30) {
                        $time_message = "Just now";
                    }
                    else {
                        $time_message = $interval->s . " seconds ago";
                    }
                }

                if($imagePath != "") {
                    $imageDiv = "<div class='postedImage'>
                                    <img src='$imagePath' onclick='openModal$id()'>
                                </div>";
                }
                else {
                    $imageDiv = "";
                }

                if($this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath) != ""){

                    $str .= $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath);

                }

                    $str .= "<div class='status_post' onClick='javascript:toggle$id()'>
                        <div class='post_profile_pic'>
                            <img src='$profile_pic' width='50'>
                        </div>

                        <div class='posted_by' style='color:#ACACAC;'>
                            <a href='$added_by'> $first_name $last_name </a> $user_to &nbsp;&nbsp;&nbsp;&nbsp;$time_message
                        </div>
                        <div id='post_body'>
                            $body
                            <br>
                            $imageDiv
                            <br>
                            <br>
                        </div>

                        <div class='modal fade' id='edit_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>

                            <div class='modal-dialog' role='document'>

                            <div class='modal-content'>

                                <div class='modal-header'>

                                    <h5 class='modal-title' id='exampleModalLabel'>Edit Your Post</h5>
                                    <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                    <span aria-hidden='true'>&times;</span>
                                    </button>

                                </div>

                                <div class='modal-body'>
                                    <p>Edit your Post</p>

                                    <form class='post_form' action='index.php' method='POST'>
                                    <div class='form-group'>

                                        <textarea class='form-control' id='post_text' name='post_text' placeholder='Got something to edit?'>$body</textarea>
                                        <input type='hidden' name='post_id' value='$id'>
                                        <button type='submit' class='btn btn-primary' name='edit' id='post_button'>Post</button>

                                    </div>

                                    </form>

                                </div>

                                <div class='modal-footer'>
                                    <button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>
                                </div>

                            </div>

                            </div>

                        </div>

                        <div class='modal fade' id='delete_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>

                            <div class='modal-dialog' role='document'>

                            <div class='modal-content'>

                                <div class='modal-header'>

                                    <h5 class='modal-title' id='exampleModalLabel'>Delete Your Post</h5>
                                    <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                    <span aria-hidden='true'>&times;</span>
                                    </button>

                                </div>

                                <div class='modal-body'>
                                    <p>Are you sure you want to Delete?</p>

                                    <form class='post_form' action='index.php' method='POST'>
                                    <div class='form-group'>

                                        <input type='hidden' name='post_id' value='$id'>
                                        <button type='submit' class='btn btn-primary' name='delete' id='post_button'>Yes!</button>

                                    </div>

                                    </form>

                                </div>

                                <div class='modal-footer'>
                                    <button type='button' class='btn btn-secondary' data-dismiss='modal'>No!</button>
                                </div>

                            </div>

                            </div>

                        </div>

                        <div class='modal fade' id='repost_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>

                            <div class='modal-dialog' role='document'>

                            <div class='modal-content'>

                                <div class='modal-header'>

                                    <h5 class='modal-title' id='exampleModalLabel'>Repost the Post</h5>
                                    <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                    <span aria-hidden='true'>&times;</span>
                                    </button>

                                </div>

                                <div class='modal-body'>
                                    <p>Repost</p>
                                    <p>\"$body\"</p>
                                    <form class='post_form' action='index.php' method='POST'>
                                    <div class='form-group'>
                                        <textarea class='form-control' id='post_text' name='post_text' placeholder='Want something to say about the Repost?'></textarea>
                                        <input type='hidden' name='post_id' value='$id'>
                                        <input type='hidden' name='repost_by' value='$userLoggedIn'>
                                        <button type='submit' class='btn btn-primary' name='repost' id='post_button'>Repost!</button>
                                    </div>

                                    </form>

                                </div>

                                <div class='modal-footer'>
                                    <button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
                                </div>

                            </div>

                            </div>

                        </div>

                        <div class='newsFeedPostOptions'>

                            Comments($comments_check_num)&nbsp;&nbsp;&nbsp;&nbsp;
                            <iframe src='like.php?post_id=$id' id='likes_iframe' scrolling='no'></iframe>
                            $delete_button
                            $edit_button
                            $repost_button

                        </div>

                    </div>
                    <div class='post_comment' id='toggleComment$id' style='display:none;'>

                        <iframe src='comment_frame.php?post_id=$id' id='comment_iframe' frameborder='0'>
                        </iframe>

                    </div>
                    <div id='myModal$id' class='imageModal' style='display: none'>
                        <div class='modalContent'>
                            <img src='$imagePath' class='modalImage'>
                            <br>
                            <button class='button cursor' onclick='closeModal$id()'>Close</button>
                        </div>
                    </div>
                    <br>";

            }

        } //End while loop

        if($count > $limit) 
            $str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
                        <input type='hidden' class='noMorePosts' value='false'>";
        else 
            $str .= "<input type='hidden' class='noMorePosts' value='true'><center><p style='text-align: centre; padding-top: 30px; color: #ACACAC '> No more posts to show! </p></center>";
    }

    echo $str;

}

A:

First I should warn you of the risks around SQL injection and that your code could be at risk depending on how you filter things like the $post_id as it could be where someone will sneak in a drop table or something like this to really ruin you day.
I strongly suggest looking at prepared statements to avoid this but more recommend looking into highly maintained libraries that abstract out the SQL building effort to more programatic building of your queries. eg Eloquent which is part of a fantastic MVC framework called Laravel but can be used independently or as part of other frameworks.
The other thing to point out is excessive queries to your database, because you have an initial query to get the reposts / post and then you iterate over the results and query for the user on each post, you're adding too many queries to the function where one query could achieve the same result. Look at using joins if you're writing the SQL manually in code or if you switch to Eloquent then relations are a fantastic way to do something called eager loading where you query one table and using the relations you ask for it to include the users or other things that are related through structure like a foreign key. All only costing you one or two queries instead of as many as n where n is the number of reposts / post.
if($this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath) != ""){
    $str .= $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath);
}

This is at risk of performing the same many queries twice where the first is to just check if there are reposts and then performs the same functional request again. Consider assigning the results of the first call to a variable and check in the condition then use that variable if true, see below.
if (!empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))) {
    $str .= $reposts;
}

You can even go so far as to just use a ternary:
$str .= (
    !empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))
        ? $reposts
        : ''
);

Now there is lots to learn but getting your SQL safe is a good starting point, efficiencies in your code will come as you discover new techniques.
As for your issue, the order in which you display the posts is possibly suffering from a programatic approach to your design, what you should really do is build up an array of your posts and reposts as objects of properties, and then when you have completed all your queries to populate the array you can use usort to re order the array based on one of its items properties ( possibly a date time property or other value you wish to sort on ) and then after sorting you can iterate over that array using a foreach and build up the HTML output in one step.
It would require a great deal of effort to provide an altered version of your code with this proposed change so instead I think you need to adjust your approach and think more about executing your code in steps and try not to start preparing your presentation of the data while you're still getting the data and instead fetch all the data, organise and reduce the data and then produce the presentation.

