我差不多完成了一个存储并让管理员操纵用户信息的网站。
我实施的最后一项功能是修改排名的能力:每个用户都有排名,您可以使用菜单通过向上或向下移动用户来手动调整排名。
它完美运行:我可以修改它,数据库正确存储新的排名;我可以添加一个新用户,它成为排名最低的用户。问题是当我尝试删除用户时。
我写了一个PHP脚本,它应该执行以下操作:
WHERE
声明以下是整个PHP:
<?php
// Connecting to the server.
$con=mysqli_connect("connection data");
$rangcounter = 1;
//deleting the user's data - works: the user's data is deleted from both tables
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$id = $_POST['playerid'];
mysqli_query($con,"DELETE FROM Player WHERE ID=$id");
mysqli_query($con,"DELETE FROM Troops WHERE ID=$id");
}
//deleting the user's image from the server - works: the user's file is deleted
$directory = 'uploads/';
unlink($directory . $id . "picture.jpg");
//updating the database - does not work: the other users' ranks stay the same as before
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY rank ASC");
while($row = mysqli_fetch_array($result)) {
$updateid = $row['ID'];
mysqli_query($con,"UPDATE Player SET 'rank' = $rangcounter WHERE ID='$updateid'");
$rangcounter++; //this variable should always be correctly high rank for any given loop. This way I can remove the highest ranked user (1st), then set every other one's rank to one less: the previously 2nd becomes the new 1st (when `$rangcounter` is 1); the previous 3rd will be the new 2nd (when `$rangcounter` is 2), and so on for every row.
}
header("redirect to main page");
exit();
?>
我的想法是创建一个新的变量,从1开始,然后,每增加UPDATE
我就增加它。因为$result
是按等级排序的,所以它应该不是问题,对吧?但它不起作用,我很确定这是因为一个简单的原因,但我不能把手指放在它上面。
你们有人可以帮忙吗?
更新:TJ-解决了它:MySQL update in a PHP While loop
答案 0 :(得分:0)
更改为
mysqli_query($con,"UPDATE Player SET rank = $rangcounter WHERE ID='$updateid'");
这
mysqli_query($con,"UPDATE Player SET 'rank' = $rangcounter WHERE ID='$updateid'");
答案 1 :(得分:0)
根据你的解释,我明白你可以
userId | rank
1 1
2 2
3 5
4 6
5 3
6 4
并删除id为3的用户后,您希望:
userId | rank
1 1
2 2
4 5
5 3
6 4
如果上述内容正确,那么您需要的只是在删除用户后执行
UPDATE Player SET rank = rank-1 WHERE rank > $theDeletedsRank
答案 2 :(得分:0)
在mysqli_query中的''
附近添加引号$rangcounter
。
mysqli_query($con,"UPDATE Player SET 'rank' = '$rangcounter' WHERE ID='$updateid'");
希望这有助于你
答案 3 :(得分:0)
不应对列名使用单引号''
。也总是在查询字符串之外使用php变量,如下所示。
请试一试。
mysqli_query($con,"UPDATE Player SET rank=".$rangcounter." WHERE ID=".$updateid."");
希望这很好。