Richard Richard - 4 months ago 9
SQL Question

PHP delete function in a forum

I have created this php file to allow users to delete posts on my forum. What i am trying to do is make sure users will be able to delete only their own posts UNLESS they are an administrator. So far users are able to delete their own posts. However Administrators cannot delete posts that they did not create and the code returns false at the DELETE query. What am i doing wrong?

user_level at 2 or higher is an administrator. 0 is for normal user.

Note: i am aware of the SQL injection vulnerabilities in this code. I will fix it once the logical part is complete.

<?php
include 'connect.php';
include 'header.php';

$id = $_GET['post_id'];

if (isset($_SESSION['signed_in'])) {

$sql= "SELECT * FROM posts WHERE post_id=$id";
$post_data=$link->query($sql);
if($post_data->num_rows > 0) {
if($row=$post_data->fetch_assoc()) {
}
}
if (!$_SESSION['user_level'] === 2 ) {

echo 'You need to be an admin to delete other peoples posts.';
}
else {

if ($_SESSION['user_id'] === $row['post_by']) {
$delsql2= 'DELETE FROM posts WHERE post_id='.$id;
$stmt2= $link->query($delsql2);
header ('Location:index.php');
}
else {
var_dump($_SESSION);
echo 'You can only delete your own posts.';
}
}
}
else {
echo 'You must be signed in to delete a post.';
}
?>

Answer

Since you need to see if the person is admin OR if it's their own post, then do that in one if:

    if (($_SESSION['user_id'] === $row['post_by']) || $_SESSION['user_level'] === 2 ) {
        $delsql2= 'DELETE FROM posts WHERE post_id='.$id;
        $stmt2= $link->query($delsql2);
        header ('Location:index.php');
    }
    else {
        var_dump($_SESSION);
        echo 'You can only delete your own posts.';
    }

This will eliminate the first (bad) if statement.