php - 如何从他的父用户标识中搜索一级用户记录

标签 php mysql

我创建了一个员工的表,所有员工都与其他员工相关联,为此,我创建了一个 parentUserId 字段来了解他的父用户。

这是我的表格截图:

enter image description here

现在我刚刚开始学习 PHP 和 MySQL,所以不知道如何使用 SELECT 查询获取第一条用户记录。例如,如果我是 Stephen Lopez 用户,我想知道谁是所有连接用户中的第一个用户。

enter image description here

我正在寻找 Phyllis Hinton 用户。是否可以使用 SQL 查询,或者我需要使用 PHP 进行循环?

最佳答案

作为从 PHP 和 mysql 开始的人,这里是一个完整的代码示例,可以满足您的需求。这里没有神奇的 SQL,而是一个 PHP 循环(带有计数限制器)重复向数据库询问连接中的父级。

<?php

/* setup your database information */
$host = 'localhost';
$user = 'db_username';
$pass = 'db_password';
$db   = 'db_name';

$link= mysqli_connect($host,$user,$pass,$db); // connect to the database
if (mysqli_connect_errno()) {                 // if fail connection... exit.
    die(mysqli_connect_error());
}

/* the function to locate the first user in the chain of connections */
function find_first_user($link,$first,$last,$max_count=10){
    $cnt=0;   // local counter as prtection to never go over the $max_count
    $parent=0; 
    $tbl='myTableName';

    // find info about the person in question via the first & last name
    $q="select parentUserId from $tbl where firstName='" . mysqli_real_escape_string($link, $first) .
        "' and lastName='" . mysqli_real_escape_string($link, $last) . "'";
    if($res=mysqli_query($link, $q)){
        list($parent)=mysqli_fetch_row($res);
    }
    // if we found a parentId, repeat looking in the chain of connections
    while($parent && ++$cnt<$max_count){
        $q="select parentUserId,firstName,lastName from $tbl where userId=".intval($parent);
        if($res=mysqli_query($link, $q)){
            list($parent,$first,$last)=mysqli_fetch_row($res);
        }
    }
    return "$first $last";
}

// example usage
print find_first_user($link,'Stephen','Lopez') . "\n";
?>

关于php - 如何从他的父用户标识中搜索一级用户记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944856/

相关文章:

php - PDO 选择具有未知列的查询?

mysql - InnoDB 性能调整

PHP/MySQL 仅在变量少于几个字符时更新

php - 将 Cakephp session 设置为数据库

php - Python:preg_replace 函数模拟

php - 如何使用 PHP 获取数据表

php - 在 mysql 数据库中插入多个字符串的更好方法

php - 锁定 Web 应用程序仅适用于内网

c# - 插入语句不起作用

javascript - DataTables 中的 PHP 重定向按钮不起作用