我几乎完成了一个存储并允许管理员操作用户信息的网站。
我实现的最后一个功能是修改排名的能力:每个用户都有一个排名,您可以使用菜单通过将用户向上或向下移动来手动调整它。
它完美地工作:我可以修改它,数据库正确地存储了新的排名;我可以添加一个新用户,它成为排名最低的用户。问题是当我尝试删除用户时。
我写了一个 PHP 脚本,它应该执行以下操作:
- 接收用户ID
- 使用
WHERE
语句从两个表中删除用户的数据 - 从服务器上删除用户上传的文件
- 更新其他用户的排名,所以如果我删除了第 3 个用户,则之前的第 4 个成为第 3 个,第 5 个将成为新的第 4 个,依此类推。最后一部分是我的代码不起作用的地方。
这是完整的 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
最佳答案
在您的 mysqli_query 中的 $rangcounter
周围添加引号 ''
。
mysqli_query($con,"UPDATE Player SET 'rank' = '$rangcounter' WHERE ID='$updateid'");
希望对你有帮助
关于php - PHP While 循环中的 MySQL 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25469054/