Delete Button to Delete a User Record PHP

4.1k Views Asked by At

The below code is all on one file named 'useraccount.php' on my website. As it currently exists, this page has a form for the logged in administrator to add a new user account, as well as a table below that displays existing accounts already in the database. I am wanting to add a 'delete' button for each existing account, and have tried various ways of incorporating this, but have yet to find a solution that works. If anyone can share some expertise with me I would greatly appreciate it. I need to know how to setup the button to carry over the database row number variable so that the php can recognize which row to delete, as well as where and how to safely execute the delete query in the php. Notes are within the code that show my partial attempt.

Current PHP Code

<?php 

require("connect.php");

if(empty($_SESSION['user']) || empty($_SESSION['adminaccess']))
{ 
    header("Location: login.php"); 
    die("Redirecting to login.php"); 
}

//BEGIN DATA FETCHING TO DISPLAY CURRENT USERS
$query = " 
    SELECT 
        id, 
        username,
        display_name, 
        email,
        admin
    FROM users 
"; 

try 
{ 
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{ 
    die("Failed to run query: " . $ex->getMessage()); 
} 

$rows = $stmt->fetchAll();
//END DATA FETCHING TO DISPLAY CURRENT USERS



//BEGIN USER DELETE FUNCTION
//IM NOT SURE HOW TO SET THIS UP, OR IF IT'S EVEN IN THE RIGHT PLACE

$id = isset($_POST['id'])?intval($_POST['id']):0;
if($id>0) { $query = "DELETE FROM users WHERE id = '$id'";
}
//END USER DELETE FUNCTION



//BEGIN FOR ADD NEW USER
if(!empty($_POST)) 
{ 
    if(empty($_POST['username'])) 
    { 
        header("Location: useraccounts.php");
        die("Redirecting to: useraccounts.php");
        $error = "Please enter a username.";
    } 

    if(empty($_POST['password'])) 
    { 
        header("Location: useraccounts.php");
        die("Redirecting to: useraccounts.php");
        $error = "Please enter a password."; 
    } 

    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) 
    { 
        header("Location: useraccounts.php");
        die("Redirecting to: useraccounts.php");
        $error = "Invalid E-Mail Address"; 
    } 

    $query = "
        SELECT 
            1 
        FROM users 
        WHERE 
            username = :username 
    "; 

    $query_params = array( 
        ':username' => $_POST['username'] 
    ); 

    try 
    { 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    $row = $stmt->fetch(); 

    if($row) 
    { 
        header("Location: useraccounts.php");
        die("Redirecting to: useraccounts.php");
        $error = "This username is already in use"; 
    } 

    $query = " 
        SELECT 
            1 
        FROM users 
        WHERE 
            email = :email 
    "; 

    $query_params = array( 
        ':email' => $_POST['email'] 
    ); 

    try 
    { 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    $row = $stmt->fetch(); 

    if($row) 
    { 
        header("Location: useraccounts.php");
        die("Redirecting to: useraccounts.php");
        $error = "This email address is already registered"; 
    } 

    $query = " 
        INSERT INTO users ( 
            username,
            display_name,
            password,
            salt,
            email,
            admin
        ) VALUES ( 
            :username,
            :display_name,
            :password,
            :salt,
            :email,
            :admin
        ) 
    "; 

    $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); 

    $password = hash('sha256', $_POST['password'] . $salt); 

    for($round = 0; $round < 65536; $round++) 
    { 
        $password = hash('sha256', $password . $salt); 
    } 

    $query_params = array( 
        ':username' => $_POST['username'],
        ':display_name' => $_POST['display_name'],
        ':password' => $password,
        ':salt' => $salt, 
        ':email' => $_POST['email'],
        ':admin' => $_POST['admin'] 
    ); 

    try 
    { 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    header("Location: useraccounts.php"); 
    die("Redirecting to useraccounts.php"); 
}
?>

Table that Displays 'Add New Account' Form

<h3>Add an Account</h3>
<form action="useraccounts.php" method="post"> 
<p class="label">Username:</p> 
    <input class="text" type="text" name="username" value="" />
<p class="label">Display Name(s):</p> 
    <input class="text" type="text" name="display_name" value="" />
<p class="label">E-Mail:</p> 
    <input class="text" type="text" name="email" value="" />
<p class="label">Password:</p> 
    <input class="text" type="password" name="password" value="" />
<p class="label">Admin Account?</p> 
    <input type="radio" id="r1" name="admin" value="0" checked="checked" /><label for="r1"><span></span>No</label>
    <input type="radio" id="r2" name="admin" value="1" /><label for="r2"><span></span>Yes</label></br>
<p class="error"><?php echo $error; ?></p>
<button class="contact" type="submit" name="submit">Create Account</button> 
</form>

Table that Displays Existing User Account

<h3>Current Accounts List</h3>
<table class="parent-accounts"> 
<tr>
    <th><h4>ID</h4></th> 
    <th><h4>Username</h4></th> 
    <th><h4>Display Name(s)</h4></th>
    <th><h4>E-Mail Address</h4></th>
    <th><h4>Admin</h4></th>
</tr>
<?php foreach($rows as $row): ?> 
<form action="useraccounts.php?id=<?php echo $id['id'];?>" method="post">
<tr>
    <td><?php echo $row['id']; ?></td> 
    <td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
    <td><?php echo htmlentities($row['display_name'], ENT_QUOTES, 'UTF-8'); ?></td>
    <td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?></td> 
    <td><?php echo htmlentities($row['admin'], ENT_QUOTES, 'UTF-8'); ?></td>
    <td><input type="submit" name="submit" value="Delete User" /></td>
</tr>
</form>
<?php endforeach; ?>
</table>
1

There are 1 best solutions below

23
On BEST ANSWER

'id' is posted by the form, and your Delete User Query seems fine. You need to execute the query. And maybe make sure you handle the deleting request before you fetching current users.

<?php 

require("connect.php");

if(empty($_SESSION['user']) || empty($_SESSION['adminaccess']))
{ 
    header("Location: login.php"); 
    die("Redirecting to login.php"); 
}

//BEGIN USER DELETE FUNCTION
//IM NOT SURE HOW TO SET THIS UP, OR IF IT'S EVEN IN THE RIGHT PLACE
if(isset($_SESSION['adminaccess']))  //if user has admin privilege
{
    $id = isset($_POST['id'])?intval($_POST['id']):0;
    if($id>0)  //if valid id for deleting is posted
    { 
      $query = 'DELETE FROM users WHERE id = '.$id;
      echo '<script>alert("Query: '.$query.'");</script>';  //debug line, remove this later
      try
      {
         $stmt = $db->prepare($query);
         $stmt->execute();
      }
      catch(PDOException $ex)
      {
         die("Failed to run query: " . $ex->getMessage()); 
      }
    }
    else
    {
       echo '<script>alert("Invalid ID: '.$id.'");</script>';  //debug line, remove this later
    }
}
else
{
    echo '<script>alert("No admin access privilege.");</script>';  //debug line, remove this later
}
//END USER DELETE FUNCTION

//BEGIN DATA FETCHING TO DISPLAY CURRENT USERS
$query = " 
    SELECT 
        id, 
        username,
        display_name, 
        email,
        admin
    FROM users 
"; 

try 
{ 
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{ 
    die("Failed to run query: " . $ex->getMessage()); 
} 

$rows = $stmt->fetchAll();
//END DATA FETCHING TO DISPLAY CURRENT USERS

..........


?>