What potential pitfalls should be avoided when handling database queries and result sets in PHP?

One potential pitfall to avoid when handling database queries and result sets in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

// Example of using prepared statements to avoid SQL injection

// Assuming $conn is a valid database connection

// Prepare a SQL statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
if ($stmt === false) {
    die($conn->error);
}

// Bind parameters
$username = $_POST['username'];
$stmt->bind_param("s", $username);

// Execute the statement
$stmt->execute();

// Get the result set
$result = $stmt->get_result();

// Fetch data from the result set
while ($row = $result->fetch_assoc()) {
    // Process the data
}

// Close the statement and connection
$stmt->close();
$conn->close();