使用php和sql向朋友分享笔记

时间:2015-12-25 02:06:36

标签: php mysql sql

我想分享一些只能由我的朋友查看的笔记。我有一个名为Friends的表,其中用户的ID是 enter image description here

我想在朋友之间分享笔记,我能够分享笔记,但是当我查看笔记时,我看到双倍因为我有2个朋友

if ($friend_query = mysql_query("SELECT * FROM `friends` WHERE `user_one`='$my_id2' OR `user_two`='$my_id2'")) {

    while ($fetch_friends = mysql_fetch_assoc($friend_query)) {
        $user_one = $fetch_friends['user_one'];
        $user_two = $fetch_friends['user_two'];


        /*QUERY FOR SHARE */
        $displaying_shared_query = mysql_query(" SELECT * FROM `share` WHERE `shared_user_ID` ='$user_one' OR `shared_user_ID` ='$user_two' ");
        while ($fetch_shared_display = mysql_fetch_assoc($displaying_shared_query)) {
            $shared_id2 = $fetch_shared_display['id']; //PRIMARY ID FOR SHARING 
            $shared_note2 = $fetch_shared_display['shared_note'];
            $shared_username2 = $fetch_shared_display['shared_username']; /*UserName of user who is sharing notes*/
            $shared_user_ID2 = $fetch_shared_display['shared_user_ID']; /*ID of user who is sharing notes */
            $shared_Time2 = $fetch_shared_display['time_shared'];


            $del_share = "  <a id='closebtn' href='delete_shared_note.php?note=$shared_id2'><span id='del_share_pix'>Delete</span></a>";
            $from_pic = '<img id="post_dp" src="/user/'.$shared_username2.
            '/display_pic.jpg">';

            //2             //2

            if ($my_id2 == $shared_user_ID2) /*if the shared note is mine than display Delete Option Or ELse Dont */ {

                echo "<span  ><a id='username_text' href='profile.php?user=$shared_user_ID2'>$shared_username2</a></span><br>";
                echo "<a id='post_userName'>$from_pic<br>";
                echo "$shared_Time2 <br>";
                echo "<div class='divbutton' id='share_border'>$shared_note2 $del_share </div><br>";

            } else if ($my_id2 != $shared_user_ID2) {
                echo "<span ><a id='username_text' href='profile.php?user=$shared_user_ID2'>$shared_username2 </a></span><br>";
                echo "<a id='post_userName'>$from_pic<br>";
                echo "$shared_Time2 <br>";
                echo "<div class='divbutton' id='share_border'>$shared_note2 </div><br>";

            }
        }
    }
  }

输出

enter image description here

2 个答案:

答案 0 :(得分:1)

这个数据模型并不是最优的,但是我认为你可以跳过你与我们分享的整个外环,并切入肉中。编写一个SQL查询,根据您与谁的关系,查找与您共享的所有内容。最好不要在循环中执行SQL查询,因为这样会以指数方式增加数据库命中率。

SELECT * FROM `share` 
WHERE `shared_user_ID`  = '$my_id2' 
OR  `shared_user_ID` 
IN ( SELECT `user_one` FROM `friends` WHERE `user_two` = '$my_id2')
OR  `shared_user_ID` 
IN ( SELECT `user_two` FROM `friends` WHERE `user_one` = '$my_id2') 

如果此查询无法解决,请告诉我,我可以安装mysql并尝试复制您的数据模型以进行验证。

答案 1 :(得分:1)

此外,更好地定位您的WHILE。否则你会越来越多倍。尝试一下,或者如果您需要更多帮助,请告诉我们。)。