简体   繁体   English

使用PHP MySQL显示来自两个SQL表的数据

[英]Display data from two sql tables using PHP mySQL

I made this Social Networking website http://friendquest.rf.gd . 我创建了这个社交网站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. 我制作了一个名为Posts and reposts的SQL表,其中posts是用户输入以显示在我的网站中的新闻提要中的数据,并且repost的工作类似于Twitter上的“共享”按钮或“ retweet”按钮。

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 - 例如,我发布了一个ID为31的帖子。现在,我的一个朋友转发了ID 31,并按照应显示的时间排序,如下所示:

Repost id 3 for Post id 31 将ID 3重新发布为ID 31
Post id 33 职位编号33
Post id 32 帖子ID 32
Post id 31 编号31

How my code displays the data when a repost is done - 重新发布完成后,我的代码如何显示数据-

Post id 33 职位编号33
Post id 32 帖子ID 32
Repost id 31 for post id 31 将ID 31重新发布为ID 31
Post id 31 编号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;

}

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. 首先,我应该警告您有关SQL注入的风险,并且您的代码可能会受到风险的影响,具体取决于您如何过滤$ post_id之类的内容,因为这可能会导致某人潜入drop table或类似的事情中而导致您的工作日趋严重。

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. 我强烈建议您查看准备好的语句来避免这种情况,但更建议您查看高度维护的库,这些库将SQL构建工作抽象为查询的更多程序化构建。 eg Eloquent which is part of a fantastic MVC framework called Laravel but can be used independently or as part of other frameworks. 例如Eloquent,它是一个出色的MVC框架Laravel的一部分,但可以独立使用,也可以作为其他框架的一部分使用。

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. 如果您是用代码手动编写SQL或切换到Eloquent,则可以使用联接,这是一种很好的方式来执行“热切加载”,即查询一个表并使用要求它包括用户或用户的关系。其他与结构相关的事物,例如外键。 All only costing you one or two queries instead of as many as n where n is the number of reposts / post. 所有这些只花费您一个或两个查询,而不是多达n个查询,其中n是重新发布/发布的次数。

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. 考虑将第一次调用的结果分配给变量,并检查条件,然后使用该变量(如果为true),请参见下文。

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. 现在有很多东西要学习,但是确保您的SQL安全是一个很好的起点,随着您发现新技术,代码的效率将会提高。

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. 至于您的问题,您显示帖子的顺序可能会受到程序设计方法的困扰,您真正应该做的是将一系列帖子和帖子重新构建为属性对象,然后完成操作所有查询以填充数组,您可以使用usort根据其项属性之一(可能是日期时间属性或您希望对其排序的其他值)对数组重新排序,然后在排序后可以使用foreach并一步一步构建HTML输出。

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. 这将需要大量的精力来提供此提议的更改的代码的变更版本,因此,我认为您需要调整方法,并更多地考虑逐步执行代码,并尝试不开始准备数据表示在您仍在获取数据而取回所有数据的同时,整理并缩小数据,然后进行演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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