0

I'm using AJAX to delete rows in my db, the ajax is fine passing the ID but I want to be able to use the session that's already present as an added field to make sure users cant delete without being logged in.

Here's my php file:

if(!isset($_SESSION['username']))
{
    echo "<p>You must be logged in to view this page.</p>";
}
else
    session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once './db/conn.php';

if(isset($_GET['delete'])) {
    $user = $_SESSION['username'];
    $sqldel = 'DELETE FROM _bookmarks WHERE bookmark_id =  :ID AND username = :USER';
    $preparedStatement = $conn->prepare($sqldel);
    $preparedStatement->execute(array(':ID' => $_GET['delete'],':USER' => $user));
}

It doesn't seem to find the session to delete it also i'm not getting any errors from the console. It worked then I logged out to try again then it stopped working. I've added session_start() to make sure but that doesn't work either.

if I go direct to the page then it says I need to be logged in which I am.

1
  • 2
    @dave Irrelevant. OP is using prepared statements. Fact check please. Commented Nov 17, 2014 at 23:38

1 Answer 1

1

Session start needs to go at the top of the page. You are checking if the $_SESSION['username'] exists before starting the session:

// Move session_start() here
session_start();

// This should now check for this session variable
if(!isset($_SESSION['username'])) {
    echo "<p>You must be logged in to view this page.</p>";
 }
else {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require_once './db/conn.php';
    if(isset($_GET['delete'])) {
        $user = $_SESSION['username'];
        $sqldel = 'DELETE FROM _bookmarks WHERE bookmark_id =  :ID AND username = :USER';
        $preparedStatement = $conn->prepare($sqldel);
        $preparedStatement->execute(array(':ID' => $_GET['delete'],':USER' => $user));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Rasclatt! (wicked name btw)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.