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

时间:2019-01-12 11:12:51

标签: php mysql

我创建了这个社交网站http://friendquest.rf.gd。我在新闻提要中遇到问题,无法解决。所以一切正常,但不是我想要的方式!我制作了一个称为发布和转发的SQL表,发布是用户输入以显示在我网站的新闻提要中的数据,转发的工作方式类似于Twitter上的共享按钮或转发按钮。

现在我希望两个表同时显示。

例如,我发布了一个ID为31的帖子。现在,我的一个朋友转发了ID 31,并按其显示的时间排序-

为帖子ID 31重新发送ID 3
职位编号33
帖子ID 32
帖子ID 31

重新发布完成后,我的代码如何显示数据-

帖子ID 33
帖子ID 32
将ID 31重新发布为ID 31
帖子ID 31

我不知道如何根据发布的时间在顶部获得转发。这是我的转发代码

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 "";
    }
}

这是我的帖子代码

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;

}

1 个答案:

答案 0 :(得分:0)

首先,我应该警告您有关SQL注入的风险,并且您的代码可能会受到风险的影响,具体取决于您如何过滤$ post_id之类的内容,因为这可能会导致某人潜入drop table或类似的事情中毁了你的一天。

我强烈建议您查看准备好的语句来避免这种情况,但更建议您查看高度维护的库,这些库将SQL构建工作抽象为查询的更多程序化构建。例如Eloquent,它是一个出色的MVC框架Laravel的一部分,但可以独立使用,也可以作为其他框架的一部分。

要指出的另一件事是对数据库的查询过多,因为您有一个初始查询来获取转发/帖子,然后遍历结果并在每个帖子中查询用户,所以添加了太多查询到一个查询可以达到相同结果的函数。如果您是用代码手动编写SQL或切换到Eloquent,则可以使用联接,这是一种很好的方式来执行“热切加载”,即查询一个表并使用要求它包括用户或用户的关系。其他与结构相关的事物,例如外键。所有这些只花费您一个或两个查询,而不是多达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);
}

存在两次执行相同多次查询的风险,第一种是仅检查是否存在重新发布,然后再次执行相同的功能请求。考虑将第一次调用的结果分配给变量,并检查条件,然后使用该变量(如果为true),请参见下文。

if (!empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))) {
    $str .= $reposts;
}

您甚至可以使用三元语言:

$str .= (
    !empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))
        ? $reposts
        : ''
);

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

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

要为此提议的更改提供代码的变更版本需要大量的精力,因此,我认为您需要调整方法并更多地考虑分步执行代码,并尝试不开始准备演示文稿在您仍在获取数据时取而代之以数据,取而代之的是获取所有数据,组织和缩小数据,然后生成演示文稿。