How can one ensure a successful connection to the database in PHP?

To ensure a successful connection to the database in PHP, you need to use the correct credentials such as the hostname, username, password, and database name. Additionally, you should handle any potential errors that may occur during the connection process to troubleshoot any issues that may arise.

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

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

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