What are the best practices for handling MySQL connections and queries in PHP?

When working with MySQL connections and queries in PHP, it is important to follow best practices to ensure efficient and secure code. One common practice is to use prepared statements to prevent SQL injection attacks and improve performance. Additionally, it is recommended to close database connections after use to free up resources.

// Establish a MySQL 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);
}

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

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