首页 > 解决方案 > How to select row from Database by ID only once

问题描述

I am trying to create an explore page for my social website and I have it kind of right. I select the posts by random order and it works but the thing is, I get the same post more than once. How do I select a post randomly by the id one time only ?

So basically I just want to load the post one time only in my explore page. Currently it could load more than once.

public function loadExplorePosts($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 = $this->con->prepare('SELECT * FROM posts WHERE deleted="0" GROUP BY id ORDER BY RAND()');
    $data_query->execute();
    $data_query_result = $data_query->get_result();
    
    if ($data_query_result->num_rows > 0) {
        $num_iterations = 0; //Number of results checked (not necasserily posted)
        $count = 1;
    
        while ($row = $data_query_result->fetch_assoc()) {
            $id = $row['id'];
            $body = $row['body'];
            $added_by = $row['added_by'];
            $date_time = $row['date_added'];
            $imagePath = $row['image'];
    
            if ($userLoggedIn == $added_by) {
                //echo "Your post";
            } else {
                     
            //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;
                }
    
                if ($num_iterations++ < $start) {
                    continue;
                }
    
                //Once 10 posts have been loaded, break
                if ($count > $limit) {
                    break;
                } else {
                    $count++;
                }
            
                $user_details_query = $this->con->prepare('SELECT first_name, last_name, profile_pic FROM users WHERE username = ?');
                $user_details_query->bind_param("s", $added_by);
                $user_details_query->execute();
                $user_details_query_result = $user_details_query->get_result();
    
                while ($row = $user_details_query_result->fetch_assoc()) {
                    $first_name = $row['first_name'];
                    $last_name = $row['last_name'];
                    $profile_pic = $row['profile_pic'];
                } ?>
                <script> 
                    function toggle<?php echo $id; ?>(event){
                            
                        var target = $(event.target);
                     
                        if (!target.is('a') && !target.is('button')) {
                            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 = $this->con->prepare('SELECT * FROM comments WHERE post_id = ?');
                $comments_check->bind_param("i", $id);
                $comments_check->execute();
                $comments_check->store_result();
                $comments_check_num = $comments_check->num_rows;
    
                //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->y == 1) {
                        $time_message = $interval->y . " yr";
                    } //1 year ago
                    else {
                        $time_message = $interval->y . " yrs";
                    } //1+ year ago
                } elseif ($interval->m >= 1) {
                    if ($interval->d == 0) {
                        $days = " ago";
                    } elseif ($interval->d == 1) {
                        $days = $interval->d . "d";
                    } else {
                        $days = $interval->d . "ds";
                    }
    
                    if ($interval->m == 1) {
                        $time_message = $interval->m . "m ". $days;
                    } else {
                        $time_message = $interval->m . "m ". $days;
                    }
                } elseif ($interval->d >= 1) {
                    if ($interval->d == 1) {
                        $time_message = "Yesterday";
                    } else {
                        $time_message = $interval->d . " days ago";
                    }
                } elseif ($interval->h >= 1) {
                    if ($interval->h == 1) {
                        $time_message = $interval->h . "hr";
                    } else {
                        $time_message = $interval->h . "hrs";
                    }
                } elseif ($interval->i >= 1) {
                    if ($interval->i == 1) {
                        $time_message = $interval->i . "min";
                    } else {
                        $time_message = $interval->i . " mins";
                    }
                } else {
                    if ($interval->s < 30) {
                        $time_message = "Just now";
                    } else {
                        $time_message = $interval->s . "sec";
                    }
                }
    
                if ($imagePath != "") {
                    $parts = explode('.', $imagePath);
                    $extension = array_pop($parts);
    
                    if ($extension == 'mp4') {
                        $imageDiv = "<div class='postedImage'>
                                     <video width='670' height='415' controls>
                                        <source src='$imagePath' type='video/mp4'>
                                    </video></div>";
                    } elseif ($extension == 'gif' || 'png' || 'jpg' || 'jpeg') {
                        $imageDiv = "<div class='postedImage'>
                                        <a data-fancybox='gallery' href='$imagePath'><img src='$imagePath'></a>
                                    </div>";
                    } else {
                        echo "Couldn't load file";
                    }
                } else {
                    $imageDiv = "";
                }
    
                $str .= "<div class='status_post' onClick='javascript:toggle$id(event)'>
                            <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='newsfeedPostOptions'>
                                Comments($comments_check_num)&nbsp;&nbsp;&nbsp;
                                <iframe src='like.php?post_id=$id' scrolling='no'></iframe>
                            </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>
                        <hr>";
            }
        } //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'><p style='text-align: centre;' class='noMorePostsText'><center> No more posts to show! </center></p><br><br>";
        }
    }
    
    echo $str;
}

标签: phpmysqlmysqli

解决方案


你应该使用类似的东西

SELECT DISTINCT column1, column2, ...
FROM table_name;

仅用于选择指定的列一次(不同)

来源:https ://www.w3schools.com/sql/sql_distinct.asp


推荐阅读