如何检查用户是否有权查看文档

时间:2015-09-22 14:00:33

标签: php mysql

我正在尝试创建一个脚本来检查用户是否有权查看文档,我使用两个数据库表进行此操作。为了列出他拥有权利的所有文件标题。

我有结果,但是当我向表格2分配文档时,可能因为在周期之外而没有显示。

如果我在循环中插入它,而每次我向Table-2 ||添加新记录时我都会得到相同的标题(例如表1中的标题1将显示4次)

表1

id | document  |
1  | Title 1   |
2  | Title 2   |
3  | Title 3   |
4  | Title 4   |

表2

id | userid  | docid  |
1  | 1       |   2    |
2  | 1       |   3    |
3  | 2       |   2    |
4  | 1       |   4    |

脚本     

        $query = "SELECT * FROM docdistributed order by id DESC";
        $result = mysql_query($query);

        while($row = mysql_fetch_array($result))
        {

        $id_distributed = $row["id"];
        $userdistributed = 1;

        $albums_query = "SELECT * FROM docacknowledge order by id DESC";
        $albums_result = mysql_query($albums_query);

        while($row1 = mysql_fetch_array($albums_result))
        {
        $id_acknowledge = $row1["docid"];
        $useracknowledge  = $row1["userid"];


        if ($id_distributed == $id_acknowledge && $userdistributed == $useracknowledge){

        $node = 0;

        } else {
        $node = 1;

        }



        }

if($node==0){
echo'<tr style="background-color:#;">';
echo'<td>'.$row["id"].'</td>';
echo'<td>'.$row["document"].'</td>';
echo'<td>';
echo'<div class="btn-group">';
echo'<button type="button" class="btn btn-sm btn-info">Action</button>';
echo'<button type="button" class="btn btn-sm btn-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false">';
echo'<span class="caret"></span>';
echo'<span class="sr-only">Toggle Dropdown</span>';
echo'</button>';
echo'<ul class="dropdown-menu" role="menu">';
echo'<li><a href="#">Open</a></li>';
echo'<li><a href="#">Download</a></li>';
echo'</ul>';
echo'</div>';
echo'</td>';
echo'</tr>';
}


if($node==1){
echo'<tr style="background-color:#FFFFDF;">';
echo'<td>'.$row["id"].'</td>';
echo'<td>'.$row["document"].'</td>';
echo'<td>';
echo'<div class="btn-group">';
echo'<button type="button" class="btn btn-sm btn-info">Action</button>';
echo'<button type="button" class="btn btn-sm btn-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false">';
echo'<span class="caret"></span>';
echo'<span class="sr-only">Toggle Dropdown</span>';
echo'</button>';
echo'<ul class="dropdown-menu" role="menu">';
echo'<form id="ack" action="ack_bulletin.php" method="post"><input type="text"  name="docid" value="'.$row["id"].'"><input type="text" name="userid" value="'.$userdistributed.'"><li onclick="ack.submit();"><a href="#">Acknowledge</a></li></form>';
echo'</ul>';
echo'</div>';
echo'</td>';
echo'</tr>';
}
        }

?>

1 个答案:

答案 0 :(得分:0)

您应该在两个数据库表上利用MySQL LEFT JOIN,这样您就不需要执行这些嵌套循环,只能在1 SELECT中获取所需的数据。尝试使用此查询:

    SELECT *
      FROM docdistributed dd
 LEFT JOIN docacknowledge da ON dd.id = da.docid
  ORDER BY dd.id DESC

这有效地取代了使用基于PHP的逻辑的需要:

if ($id_distributed == $id_acknowledge && $userdistributed == $useracknowledge) {

反过来又可以防止所描述的困境,因为你可以在脚本的某些接合点处获得哪些关系数据。