What are the best practices for updating and deleting user information in real-time in a PHP application?

When updating or deleting user information in real-time in a PHP application, it is important to properly validate user input, sanitize data to prevent SQL injection attacks, and handle errors gracefully. Additionally, using prepared statements can help protect against SQL injection vulnerabilities and ensure data integrity.

// Update user information
if(isset($_POST['update_user'])) {
    $user_id = $_POST['user_id'];
    $new_name = $_POST['new_name'];
    
    $stmt = $pdo->prepare("UPDATE users SET name = :new_name WHERE id = :user_id");
    $stmt->bindParam(':new_name', $new_name);
    $stmt->bindParam(':user_id', $user_id);
    
    if($stmt->execute()) {
        echo "User information updated successfully.";
    } else {
        echo "Error updating user information.";
    }
}

// Delete user
if(isset($_POST['delete_user'])) {
    $user_id = $_POST['user_id'];
    
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    
    if($stmt->execute()) {
        echo "User deleted successfully.";
    } else {
        echo "Error deleting user.";
    }
}