How can the issue of displaying text twice be resolved when establishing a connection to a database in PHP?

The issue of displaying text twice when establishing a connection to a database in PHP can be resolved by ensuring that the connection is only established once in the code. This can be achieved by using a conditional check to see if the connection has already been established before attempting to establish it again.

<?php
// Check if the connection is already established
if (!isset($connection)) {
    // Establish the connection to the database
    $connection = mysqli_connect("localhost", "username", "password", "database");
    
    // Check if the connection was successful
    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }
}
?>