How can the code be modified to prevent the page from loading indefinitely and improve its functionality?

The issue of the page loading indefinitely can be solved by setting a timeout for the database connection. This will prevent the script from waiting indefinitely for a response. By implementing a timeout, the script will stop trying to connect to the database after a specified period of time and can handle the error accordingly.

// Set a timeout for the database connection
$connection = mysqli_init();
$connection->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); // Set timeout to 10 seconds

// Connect to the database
$connection->real_connect($host, $username, $password, $database);

// Check if the connection was successful
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
} else {
    echo "Connected successfully";
}