What are best practices for handling database connections and queries in PHP to ensure proper functionality?

When handling database connections and queries in PHP, it is important to properly open and close connections to avoid potential memory leaks and ensure efficient resource management. It is also crucial to use prepared statements to prevent SQL injection attacks and improve query performance. Additionally, consider implementing error handling to gracefully manage any database-related errors that may occur.

// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example_user";
$stmt->execute();

$result = $stmt->get_result();

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

// Closing the database connection
$stmt->close();
$conn->close();