几年前,SO 用户帮助我构建了以下代码以在组中分配“合作伙伴”(如循环 [A->B->C->D->A->B->...] ):
$q = "SELECT user_id FROM users WHERE group_id='$gi' ORDER BY RAND()";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
while ($row = mysqli_fetch_array($r)) {
$users[] = $row[0];
}
$current = end($users);
$partners = array();
foreach ($users as $user) {
$partners[$user] = $current;
$current = $user;
$q="UPDATE users SET partner='{$partners[$user]}' WHERE user_id='{$user}'";
mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
}
然而,现在我正在用 PDO 重写我的大部分代码,而数组正在杀死我。到目前为止,这是我重写此内容的最佳尝试:
$query = "SELECT id FROM users WHERE gid=:gid ORDER BY RAND()";
$query_params = array( ':gid' => $_SESSION['user']['gid'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
while ($row = $stmt->fetchAll(PDO::FETCH_COLUMN)) {
$users[] = $row[0];
}
$current = end($users);
$partners = array();
foreach ($users as $user) {
$partners[$user] = $current;
$current = $user;
$query = "UPDATE users SET partner=:partner WHERE id=:id";
$query_params = array(
':partner' => '{$partners[$user]}',
':id' => '{$user}'
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
我所有的阅读和搜索都没有得到关于为什么我的修改后的代码不再有效的答案。 现在发生的所有事情都是将一个用户自己分配为合作伙伴,而不是循环分配合作伙伴。
据我所知,我的fetchAll
陈述是不正确的,但是如何?对于我的一生,我无法弄清楚。
(如果你提出一种更有效的方法来做这件事,我不会感到不安。)