How can the 'SQLSTATE[HY000] [2002] Connection refused' error be resolved in PHP?

The 'SQLSTATE[HY000] [2002] Connection refused' error occurs when PHP is unable to connect to the MySQL database server. This can be due to incorrect database credentials, server configuration issues, or the database server not running. To resolve this error, ensure that the database credentials in your PHP code are correct, the database server is running, and there are no firewall restrictions blocking the connection.

// Example PHP code to resolve 'SQLSTATE[HY000] [2002] Connection refused' error
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

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