我使用AJAX删除我的数据库中的行,ajax可以很好地传递ID,但我希望能够使用已经存在的会话作为添加字段以确保用户无法使用删除而不登录。
这是我的php文件:
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));
}
它似乎没有找到要删除它的会话,我也没有从控制台收到任何错误。它工作然后我退出再试一次然后它停止工作。我已经添加了session_start()以确保这一点,但这也不起作用。
如果我直接进入页面,那么它说我需要登录,我就是。
答案 0 :(得分:1)
会话开始需要位于页面顶部。在开始会话之前,您正在检查$_SESSION['username']
是否存在:
// 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));
}
}