[英]Deleting Row from users table PHP MYSQL
我想在用戶點擊按鈕時從我的用戶表中刪除一行,用戶需要登錄才能刪除自己的帳戶。
我已經回顯了$ user_id,它顯示了'4',這是登錄用戶的正確ID,所以user_id = $ user_id
這是我擁有按鈕的頁面,我想刪除數據庫中的用戶行
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Welcome - <?php print($userRow['user_email']); ?></title>
</head>
<body>
<div class="header">
<div class="right">
<label><a href="logout.php?logout=true"><i class="glyphicon glyphicon-log-out"></i> logout</a></label>
</div>
</div>
<div class="content">
Welcome <?php print($userRow['user_name']); ?> <br>
<?php print($userRow['team_name']);?><br>
Rank <?php print($userRow['user_rank']); ?> <br>
<a href="players.php">Players</a>
<a href="teams.php">Teams</a>
<form action='teams.php' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
<?php echo $user_id?>
</div>
</body>
</html>
我認為您的問題是您的表單操作(teams.php)將收到帖子數據。您的刪除代碼在同一個文件上,邏輯上$ _POST ['leave']將永遠不會在此頁面中設置。
只是嘗試在您的表單操作屬性中刪除您的teams.php。
<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
或者在teams.php文件中添加刪除代碼
//Make sure you have started the session before using it
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
另一條建議是使用參數化查詢。 例:
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = ? ");
$stmt-> bindParam(1,$user_id);
$stmt->execute();
}
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} ?>
<a href="?id=<?php echo $id;?>" onclick="return confirm('Are you sure?')">Delete</a>
<?php if(isset($_GET['id'])){
$user_id = $_SESSION['user_session'];
$id=$_GET['id'];
if($id==$user_id){
$sql = "DELETE FROM Tablename WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
}?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.