2 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
要在數(shù)據(jù)庫(kù)中切換用戶類型,您需要獲取用戶 ID 和用戶的當(dāng)前角色。然后您必須將這些信息發(fā)送到 php 腳本以切換數(shù)據(jù)庫(kù)中的用戶角色。
假設(shè)我們有一個(gè)名為 toggleUser.php 的 php 文件,它使用 get 方法接收用戶 ID 和當(dāng)前角色,那么你的 url 將如下所示:
<a class="btn btn-danger" href="toggleUser.php?userid=<?php echo $row['userid']?>&role=<?php echo $row['role']?>">Toggle Admin</a>
創(chuàng)建文件 toggleUser.php 并添加以下代碼:
<?php
$userid = $_GET['userid'];
$role = $_GET['role'];
$role = ($role==1)?0:1;
$stmt = mysqli_prepare($conn, "update accounts set IsAdmin=? where username=?");
mysqli_stmt_bind_param($stmt, 'ss', $role,$userid);
mysqli_stmt_execute($stmt);
header("location:showusers.php");
?>

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
您實(shí)際上也可以使用 PHP 解決問(wèn)題。
我假設(shè)“用戶名”字段是唯一的。我通過(guò)將“Toggle Admin”放入由同一文件處理的表單中修改了您的代碼的某些部分。單擊按鈕后,將執(zhí)行添加到 PHP 塊的代碼。該代碼從表單接收用戶名和當(dāng)前角色,然后相應(yīng)地切換數(shù)據(jù)庫(kù)中的“IsAdmin”。這是我的解決方案:
<b><?php
echo $row['username'];
?></b>
<form action="" method="post">
<input type="hidden" name="username" value="{$row['username']}">
<input type="hidden" name="role" value="{$row['IsAdmin']}">
<input type="submit" name="toggle_admin" class="btn btn-danger" value="Toggle Admin">
</form>
我還按如下方式更新了您的 PHP 塊:
<?PHP
include("auth.php");
require_once "config.php";
$result = mysqli_query($conn, "SELECT * FROM accounts");
// Execute this code if the 'Toggle Admin' button is clicked
if (isset($_POST['toggle_admin']))
{
if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['role']) && !empty($_POST['role']))
{
// Retrieve necessary inputs
$username = htmlentities($_POST['username']);
$role = htmlentities($_POST['role']);
// Toggle Admin
if ($role == 0)
{
// Set user to be admin if not currently admin
$IsAdmin = 1;
}
else
{
// Set user to be non admin if user is currently admin
$IsAdmin = 0;
}
// Update the database accordingly.
$perform_toggle_admin = mysqli_query($conn, "UPDATE accounts SET IsAdmin = '$IsAdmin' WHERE username = '$username'");
}
}
?>
希望這是有幫助的。
- 2 回答
- 0 關(guān)注
- 130 瀏覽
添加回答
舉報(bào)