从用户表中删除行PHP MYSQL

时间:2015-12-14 03:29:18

标签: php mysql sql-delete

我想在用户点击按钮时从我的用户表中删除一行,用户需要登录才能删除自己的帐户。

我已经回显了$ 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>

2 个答案:

答案 0 :(得分:5)

我认为您的问题是您的表单操作(teams.php),它会收到帖子数据。您的删除代码位于同一个文件中,逻辑上$ _POST ['leave']将永远不会在此页面中设置。

尝试在您的表单操作属性中删除您的teams.php。

for (int count2; count2 < 30; count2++)
{
  acct[count2] = new Account(owner, count2, 0);
}

或在您的teams.php文件中添加删除代码

<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>

另一条建议是使用参数化查询。  例如:

//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();
}

答案 1 :(得分:0)

<?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;
            }

        }
    }?>