What best practices should be followed when handling database connections and queries in PHP code?

When handling database connections and queries in PHP code, it is important to follow best practices to ensure security, efficiency, and maintainability. This includes using prepared statements to prevent SQL injection attacks, closing connections after use to free up resources, and handling errors properly to avoid exposing sensitive information.

// 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 = "john_doe";
$stmt->execute();
$result = $stmt->get_result();

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

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