What could be potential reasons for a "Connection refused" error when trying to connect to a MySQL server in PHP?
The "Connection refused" error in PHP when trying to connect to a MySQL server could be due to incorrect server settings, firewall restrictions, or the MySQL server not running. To solve this issue, ensure that the MySQL server is running, check the server host, username, password, and port in the connection settings, and verify that the server allows connections from the PHP application.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>