根据两个相关的数据库表打印两个列表

Print two lists based on two related database tables

我有这 2 个 while 循环。

  1. 循环。左侧屏幕。显示附加到任务的用户。

    $getcurrentusers = $conn->prepare("SELECT u.userid, u.username, u.Fname, u.inactive, r.userid, r.job_id FROM users AS u INNER JOIN job_responsible AS r ON u.userid = r.userid WHERE u.inactive = 0 AND r.job_id = $getPostID ORDER BY u.Fname");
    $getcurrentusers->execute();
    $resultgetcurrentusers = $getcurrentusers->get_result();
    $getcurrentusers->close();
    if ($resultgetcurrentusers->num_rows > 0) {
        while($row = $resultgetcurrentusers->fetch_assoc()) {
            echo $row["username"]." (".$row["Fname"].")<br />";
        }
    } else {
        echo "Der er ikke valgt nogle ansvarlige til denne opgave.";
    }
    
  2. 循环。右侧屏幕。列出所有可以添加到任务的可能用户

    $getdepartmentview = $SetDepartmentView;
    $explodegetdepartmentview = explode(",",$getdepartmentview);
    $implodegetdepartmentview = "'".implode("','",$explodegetdepartmentview)."'";
    $getusers = $conn->prepare("SELECT userid, username, Fname, inactive FROM users WHERE departmentid IN ($implodegetdepartmentview) AND inactive = 0 ORDER BY Fname");
    $getusers->execute();
    $resultgetusers = $getusers->get_result();
    $getusers->close();
    if ($resultgetusers->num_rows > 0) {
        while($row = $resultgetusers->fetch_assoc()) { 
            echo "<input type=\"checkbox\" name=\"choose_responsible[]\" value=\"".$row["userid"].",\" />".$row["Fname"]."<br />";
        } 
    }
    

问题是,我真的很想,当左侧有匹配项时,输入复选框在右侧 'checked'。循环。

所以..

Loop 1 | Loop 2
name3  | name1
name5  | name2
name7  | name3 - Inputbox checked
name8  | name4
       | name5 - Inputbox checked
       | name6
       | name7 - Inputbox checked
       | name8 - Inputbox checked
       | name9
       | name10

在第一个循环中,您可以将 user_id 存储在一个数组中

$user_ids[] = $row["userid"]

在第二个循环中,您检查当前用户 ID 是否存在于之前保存的 $user_ids 数组

$checked = false;
if (in_array($row["userid"], $user_ids)) {
    $checked = true;
} 

此任务在单个查询中调用 LEFT JOIN 以避免多次访问数据库并避免对结果集进行低效的 php 处理。

$sql = <<<SQL
SELECT u.userid,
       u.username,
       u.Fname,
       u.inactive,
       r.userid responsibleUserId,
       r.job_id
FROM users AS u
LEFT JOIN job_responsible AS r
    ON u.userid = r.userid
        AND r.job = ?
WHERE u.inactive = 0
ORDER BY u.Fname
SQL;

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $getPostID);
$result = $stmt->execute();
$users = $result->fetch_all(MYSQLI_ASSOC);

现在您拥有所需的所有数据,因此没有更多理由访问数据库。

要列出分配给目标工作的用户,请迭代关联数组的数组并向用户显示 job_id 不为空的位置。

foreach ($users as $user) {
    if ($user['job_id']) {
        printf('%s (%s)<br />', $user['username'], $user['Fname']);
    }
}

要显示所有用户并有条件地选中已经“负责”的名称旁边的复选框,请再次迭代数组并依靠 job_id 来确定复选框。

foreach ($users as $user) {
    printf(
        '<input type="checkbox" name="choose_responsible[]" value="%d"%s/>%s<br />',
        $user['userid'],
        $user['job_id'] ? ' checked' : '',
        $user['Fname']
    );
}