What are the best practices for handling database results in PHP to avoid unnecessary queries?

When handling database results in PHP, it's important to avoid unnecessary queries to improve performance. One way to achieve this is by storing the results in variables or arrays and reusing them instead of querying the database multiple times for the same data.

// Example of storing database results in a variable to avoid unnecessary queries

// Query the database for user information
$userQuery = "SELECT * FROM users WHERE id = 1";
$userResult = mysqli_query($connection, $userQuery);
$userData = mysqli_fetch_assoc($userResult);

// Reuse the $userData variable instead of querying the database again
echo "Username: " . $userData['username'];
echo "Email: " . $userData['email'];