What are the best practices for connecting to a MySQL database in PHP?

When connecting to a MySQL database in PHP, it is important to use the mysqli extension for improved security and performance. It is recommended to use prepared statements to prevent SQL injection attacks. Additionally, always remember to close the database connection after use to free up resources.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Perform database operations here

// Close connection
$conn->close();
?>