如何从子用户获取数据

时间:2016-12-08 01:53:56

标签: php sql function tree php-mysqlidb

我正在创建一个程序,其中每个用户都有一个父用户(用户树)。每个父用户都可以查看子用户持有的所有数据。 这一次,要查看子用户的所有现有数据,我使用如下脚本:

    $query = "select * from com_oportunity where asign_to='$lcode' ";
    $gsql=mysql_query("select a.id, b.code from com_roles a, com_users b where   a.parent_id='$lrole' and a.id=b.role");
    while($grow=mysql_fetch_row($gsql)){
        $query.=" or  asign_to='".$grow[1]."' ";
            $checksql=mysql_query("select a.id, b.code from com_roles a, com_users b where a.parent_id='$grow[0]' and a.id=b.role");
            $checksqlnum=mysql_num_rows($checksql);
            if($checksqlnum!=0){
            while($checkrow=mysql_fetch_row($checksql)){
            $query.=" or  asign_to='".$checkrow[1]."' ";
                $checksql2=mysql_query("select a.id, b.code from com_roles a, com_users b where a.parent_id='$checkrow[0]' and a.id=b.role");
                $checksqlnum2=mysql_num_rows($checksql2);
                if($checksqlnum2!=0){
                while($checkrow2=mysql_fetch_row($checksql2)){
                $query.=" or  asign_to='".$checkrow2[1]."' ";
                }
                }
            }
            }
    }
$query.=" order by id";

$sql=mysql_query($query);

脚本限制为3级用户的深度;如果我想拥有无限深度的用户,我该如何简化上面的脚本?

1 个答案:

答案 0 :(得分:0)

您应该能够使用JOIN子句(注意:该链接指向MySQL参考,但大多数其他数据库引擎也支持JOIN - 例如MS SQL Server,PostgreSQL等)。

另请注意,在下面的示例中,我更新了mysql_query()和类似函数,以使用mysqli_ *函数代替...根据文档:

  

警告此扩展在PHP 5.5.0中已弃用,并已在PHP 7.0.0中删除。相反,应使用MySQLiPDO_MySQL扩展名。

e.g。

$sqlText = "SELECT DISTINCT o.* FROM com_oportunity o JOIN com_users u on o.asign_to = u.code JOIN com_roles r on (r.id = u.role OR r.parent_id = u.role) order by o.id";
//replace these values with the values you need
$server = 'server_name_or_address_here';
$user = 'username';
$password = 'passwordForUsername';
$database = 'databaseName';
$connection =    mysqli_connect($server,$user,$pass,$database);

$updatedQuery = "SELECT DISTINCT o.* 
    FROM com_oportunity o 
    JOIN com_users u on o.asign_to = u.code 
    JOIN com_roles r on (r.id = u.role OR r.parent_id = u.role)
    order by o.id"; 
$sql=mysqli_query($connection, $updatedQuery);
if ($sql && mysqli_num_rows($sql)) {
    while($row=mysqli_fetch_row($sql)){
        echo 'row: '.print_r($row,1).'<br />';
    }
}
else {
    echo 'query returned false: '.$sql.'|<br/>';
}