What best practices should be followed when handling MySQL connections in PHP scripts?

When handling MySQL connections in PHP scripts, it is important to follow best practices to ensure efficient and secure database operations. One common best practice is to establish a connection to the database only when needed and close the connection after the operation is completed. Additionally, using prepared statements can help prevent SQL injection attacks and improve performance.

// Establishing a MySQL database connection
$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();