Php 如何仅按ID从数据库中选择一行

Php 如何仅按ID从数据库中选择一行,php,mysql,mysqli,Php,Mysql,Mysqli,我正在尝试为我的社交网站创建一个探索页面,我是对的。我按随机顺序选择帖子,效果不错,但问题是,我不止一次收到同一篇帖子。如何仅凭id随机选择一篇文章 所以基本上我只想在我的浏览页面中加载一次帖子。目前,它可以加载多次 public function loadExplorePosts($data, $limit) { $page = $data['page']; $userLoggedIn = $this->user_obj->getUsername();

我正在尝试为我的社交网站创建一个探索页面,我是对的。我按随机顺序选择帖子,效果不错,但问题是,我不止一次收到同一篇帖子。如何仅凭id随机选择一篇文章

所以基本上我只想在我的浏览页面中加载一次帖子。目前,它可以加载多次

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;
}
公共函数loadExplorePosts($data,$limit){
$page=$data['page'];
$userLoggedIn=$this->user_obj->getUsername();
如果($page==1){
$start=0;
}否则{
$start=($page-1)*$limit;
}
$str=”“;//要返回的字符串
$data\u query=$this->con->prepare('SELECT*FROM posts WHERE deleted=“0”GROUP BY id ORDER BY RAND());
$data_query->execute();
$data\u query\u result=$data\u query->get\u result();
如果($data\u query\u result->num\u rows>0){
$num_iterations=0;//检查的结果数(不必过账)
$count=1;
而($row=$data\u query\u result->fetch\u assoc()){
$id=$row['id'];
$body=$row['body'];
$added_by=$row['added_by'];
$date_time=$row['date_added'];
$imagePath=$row['image'];
如果($userLoggedIn==$added\u by){
//回应“你的帖子”;
}否则{
//将用户_准备为字符串,以便即使未发布给用户也可以将其包括在内
如果($row['user_to']==“none”){
$user_to=“”;
}否则{
$user_to_obj=新用户($this->con,$row['user_to']);
$user_to_name=$user_to_obj->getFirstAndLastName();
$user_to=“to”;
}
//检查发布的用户是否已关闭其帐户
$added_by_obj=新用户($this->con,$added_by);
如果($added_by_obj->isClosed()){
继续;
}
如果($num_iterations++<$start){
继续;
}
//加载10个帖子后,中断
如果($count>$limit){
打破
}否则{
$count++;
}
$user\u details\u query=$this->con->prepare('SELECT first\u name,last\u name,profile\u pic FROM username=?'的用户);
$user\u details\u query->bind\u param(“s”,由$added\u添加);
$user\u details\u query->execute();
$user\u details\u query\u result=$user\u details\u query->get\u result();
而($row=$user\u details\u query\u result->fetch\u assoc()){
$first_name=$row['first_name'];
$last_name=$row['last_name'];
$profile_pic=$row['profile_pic'];
} ?>
功能切换(事件){
var target=$(event.target);
如果(!target.is('a')&&!target.is('button')){
var元素=document.getElementById(“toggleComment”);
if(element.style.display==“块”)
element.style.display=“无”;
其他的
element.style.display=“块”;
}
}

如果尝试使用以下子查询:


SELECT*FROM(SELECT*FROM posts WHERE deleted=“0”ORDER BY rand())按id分组

SELECT DISTINCT column1, column2, ...
FROM table_name;
它仅用于选择指定的列一次(不同)


来源:

这似乎只获得一条给定的记录一次,你是否多次调用它,这就是导致重复的原因?我认为@Funkyfortyniner“有时你需要同时使用这两条记录”没有我的经验,因此很难检查你的代码,并确定在哪一点上你会看到双重结果。这不是mysqlihat给你双重结果。它是你的PHP/HTML显示它两次。仍然两次加载相同的帖子。我不知道为什么会有随机的向下投票。你可以使用DISTINCT,但group by是一种优雅的方法。我也不知道。group by也是一种可能的方法。但是另一个问题是为什么帖子会加载两次。@TarikWeiss我应该发布吗“他知道整个功能吗?”那家伙是的,请。你所说的应该只给你唯一的记录