How can the functionality of deleting individual items from a shopping cart or database table be implemented securely in PHP, considering user interactions and data validation?

When deleting individual items from a shopping cart or database table in PHP, it is essential to validate user inputs and ensure that the user has the proper permissions to delete the item. To do this securely, you can use prepared statements to prevent SQL injection attacks and verify that the item being deleted belongs to the user making the request.

// Check if the user is logged in and has the necessary permissions
if(isset($_SESSION['user_id']) && isset($_POST['item_id'])) {
    $user_id = $_SESSION['user_id'];
    $item_id = $_POST['item_id'];

    // Validate the item_id to prevent SQL injection
    if(!is_numeric($item_id)) {
        die("Invalid item ID");
    }

    // Check if the item belongs to the user
    $query = "SELECT * FROM items WHERE user_id = ? AND id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$user_id, $item_id]);
    $item = $stmt->fetch();

    if($item) {
        // Delete the item from the database
        $delete_query = "DELETE FROM items WHERE id = ?";
        $delete_stmt = $pdo->prepare($delete_query);
        $delete_stmt->execute([$item_id]);

        echo "Item successfully deleted";
    } else {
        echo "Item not found or you do not have permission to delete it";
    }
} else {
    echo "You do not have permission to perform this action";
}