What are some best practices for testing and troubleshooting MySQL connections in PHP?

Issue: When working with MySQL connections in PHP, it is important to test and troubleshoot the connection to ensure it is functioning correctly. This can help identify any issues with the connection and prevent errors in accessing the database.

// Test and troubleshoot MySQL connection in PHP
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

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

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