What best practices should be followed when managing database connections in PHP scripts?

When managing database connections in PHP scripts, it is important to follow best practices to ensure efficient and secure handling of connections. This includes establishing a connection only when needed, closing connections after use, using prepared statements to prevent SQL injection attacks, and properly handling errors.

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

// Perform database operations

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