更好的检查方法如果用户为帖子添加了书签

时间:2014-04-22 05:44:27

标签: php mysql

我正在为网站做一个小书签功能,用户可以为帖子添加书签。当用户为帖子添加书签时,会将其添加到表格postMarks

我目前的做法是打印表格posts中的主要帖子,然后从表格select count()打印每个postMarkspostId = id的{​​{1}} 。是否有更好,更有效的方法来执行此操作,而不是运行两个单独的语句。我这样做的方式效率很低。

我的所有代码都在下面。由于这仍然没有实现,我可以进行更改。

帖子

userId = currentUser

邮戳

"id"    "postTitle"
"1"     "Title 1"
"2"     "Title 2"
"3"     "Title 3"
"4"     "Title 4"
"5"     "Title 5"
"6"     "Title 6"
"7"     "Title 7"
"8"     "Title 8"
"9"     "Title 9"
"10"    "Title 10"

我的代码

"id"    "postId"    "postTitle" "userId"    "addDate"
"1"     "1"         "Title 1"   "1"         "2014-04-22 09:57:35"
"2"     "2"         "Title 2"   "1"         "2014-04-22 09:58:10"
"3"     "3"         "Title 3"   "1"         "2014-04-22 09:58:12"
"4"     "4"         "Title 4"   "1"         "2014-04-22 09:58:25"
"5"     "5"         "Title 5"   "1"         "2014-04-22 09:58:37"
"6"     "1"         "Title 1"   "2"         "2014-04-22 09:59:10"
"7"     "2"         "Title 2"   "2"         "2014-04-22 09:59:20"
"8"     "1"         "Title 1"   "3"         "2014-04-22 09:59:33"
"9"     "2"         "Title 2"   "3"         "2014-04-22 09:59:45"
"10"    "3"         "Title 3"   "3"         "2014-04-22 09:59:53"

结果

$userId = 1;

$pageData = 'select id, postTitle from posts LIMIT 10';

$stmt = $conn->prepare($pageData);

$stmt->execute();

$stmt->bindColumn(1,$a);
$stmt->bindColumn(2,$b);

$posts = $stmt->rowCount();

if($posts >= 1) {

    while($rows = $stmt->fetch(PDO::FETCH_BOUND)) {
        echo $a.' '.$b;

        // Bookmarks
        $bookMarks = "select count(postId) from postMarks where postId = '".$a."' and userId = '".$userId."'";

        $stmtx = $conn->prepare($bookMarks);

        $stmtx->execute();

        $stmtx->bindColumn(1,$a);

        $stmtx->fetch();

        if($a == 1) {
            echo ' Bookmarked <br>';
        } else {
            echo ' Not Bookmarked <br>';
        }           
        // Bookmarks detect ends
    }

} else {
    echo 'Nothing to display ';
}

1 个答案:

答案 0 :(得分:1)

我用连接更新了你的sql查询。如果当前用户为该页面添加了书签,您现在应该可以获得一个bool。

$pageData = 'SELECT
                    id,
                    postTitle,
                    IF( count(distinct postMarks.userId) > 0, true, false) as bookmarkByUser
             FROM 
                    postsLEFT JOIN postMarks ON posts.id=postMarks.postId AND userId =".$userId."
             GROUP BY
                    post.idLIMIT 10';