0

我知道这可能看起来很具体,但我是 PDO 数据库连接的新手,我不得不重写这个组件。我使用 Php microtime 来检查我的代码的哪一部分加载缓慢,并将其缩小到下面的函数(从类文件中调用)。你能帮我弄清楚这段代码效率低下的部分是什么吗?我的其余函数也使用 PDO,有些还查看连接表而没有任何性能问题。

   public function GetRecentActivity($user = null, $length = 20){
    global $pdo;

    if($user==null){
        $user = ((isset($_SESSION['UserID']))?$_SESSION['UserID']:FALSE);
        }
    if($user==FALSE){
        return -1;
        }

    $actions = array();

    $courses = $pdo->prepare("SELECT courses.courseID, courses.courseName FROM courses INNER JOIN courseRoles on courses.courseID = courseRoles.courseID WHERE courseRoles.userRole != 'Blocked' AND courseRoles.userID = :user");
    if(!$courses->execute(array(':user'=>$user)))
        return -1;
    // now we have an array of [courseID, courseName]
    //prepare some statements for the big loop
    $discs = $pdo->prepare("SELECT dID, dTitle, courseDiscussions.courseDiscussionTime FROM discussions INNER JOIN courseDiscussions on discussions.dID = courseDiscussions.discussionID WHERE courseDiscussions.courseID = :cID");
    $last = $pdo->prepare("SELECT logTime from logs WHERE logAction = 'view' AND logUserID = :user AND logPageID = :dID ORDER BY logTime DESC LIMIT 1");
    $posts = $pdo->prepare("SELECT postAuthorID, postMessage, postTime, users.firstName, postID, postType FROM posts INNER JOIN users ON posts.postAuthorID = users.userID WHERE postID IN (SELECT logActionID FROM logs INNER JOIN discussionPosts ON discussionPosts.postID = logs.logActionID WHERE logs.logAction = 'addPost' AND logs.logTime > :lastView AND logs.logPageID = :dID)");
    while($row = $courses->fetch()){
        $cID = $row['courseID'];
        if(!$discs->execute(array(':cID'=>$cID)))
            return -1;
        while($d_row = $discs->fetch()){
            $dID = $d_row['dID'];
            //find out when the user last visited this disucssion
            $last->execute(array(':user'=>$user,':dID'=>$dID));
            $lastView = $last->fetch();
            $lastView = $lastView['logTime'];
            if(empty($lastView)){
                $lastView = $d_row['courseDiscussionTime'];                 
            }
            $posts->execute(array(':lastView'=>$lastView,':dID'=>$dID));
            while($p_row = $posts->fetch()){
                $path = "/discussion.php?c=".$cID."&d=".$dID."&p=".$p_row['postID'];
                array_push($actions, array("action" => 'post',"actionTime" =>$p_row['postTime'], "actionType" =>$p_row['postType'], "context" =>'discussion', "contextLabel" =>$d_row['dTitle'] ,"contextID" =>$dID, "agentLabel" => $p_row['firstName'], "agentID" =>$p_row['postAuthorID'], "content" =>substr($p_row['postMessage'],0,120), "actionPath" =>$path)); 
            }
        }
    }
    usort($actions, function($a,$b){
        return strtotime($b['actionTime']) - strtotime($a['actionTime']);
    });
    $actions = array_slice($actions,0,$length);

    return $actions;
}
4

0 回答 0