How can PHP sessions be utilized to enhance security measures when deleting data from a database through user interaction?
When deleting data from a database through user interaction, it is important to verify the user's identity and authorization to prevent unauthorized deletions. PHP sessions can be utilized to store user authentication information, such as user ID or role, and check this information before executing the delete operation.
// Start the PHP session
session_start();
// Check if the user is logged in and has the necessary permissions
if(isset($_SESSION['user_id']) && $_SESSION['role'] == 'admin') {
// Proceed with deleting data from the database
// Example code to delete a record from a database table
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->prepare("DELETE FROM mytable WHERE id = :id");
$stmt->bindParam(':id', $_POST['id']);
$stmt->execute();
echo "Data deleted successfully.";
} else {
echo "Unauthorized access.";
}