What are the best practices for handling PDO queries and assigning values to associative arrays in PHP?

When handling PDO queries in PHP, it's important to properly prepare and execute the query to prevent SQL injection attacks. When assigning values to associative arrays, it's best practice to use named placeholders in the query and bind the values to these placeholders. This ensures that the data is sanitized and secure before being inserted into the database.

// Assuming you have already established a PDO connection

// Prepare the query with named placeholders
$query = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind the values to the named placeholders
$id = 1;
$query->bindParam(':id', $id);

// Execute the query
$query->execute();

// Fetch the results into an associative array
$user = $query->fetch(PDO::FETCH_ASSOC);

// Access the values in the associative array
echo $user['username'];