Home  >  Article  >  Database  >  Why Am I Getting a 'Connection Refused' Error When Connecting to MySQL with PHP?

Why Am I Getting a 'Connection Refused' Error When Connecting to MySQL with PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 18:03:03618browse

Why Am I Getting a

Troubleshooting MySQL Connection Issue: "Connection Refused"

When attempting to establish a MySQL connection using PHP's mysqli_connect function, you may encounter the error message "Connection refused." This typically indicates an issue with the connection parameters or server configuration.

Diagnosing the Problem

To resolve this issue, follow these steps:

  1. Verify Server Parameters: Ensure that the servername, username, and password provided to mysqli_connect match the correct database credentials.
  2. Check Port Configuration: By default, MySQL in MAMP uses port 8889, while PHP expects port 3306. If you have not modified this setting, open MAMP's preferences, navigate to MySQL, and change the port to 3306.
  3. Restart MySQL Server: After changing the port, ensure that you restart the MySQL server from within MAMP. This step is crucial for the changes to take effect.

Example:

The following code demonstrates a successful connection after adjusting the port:

$servername = "127.0.0.1";
$username = "root";
$password = "root";

// Set MySQL port to 3306
$port = 3306;

// Create connection
$conn = mysqli_connect($servername, $username, $password, null, $port);

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

By following these steps, you should be able to establish a successful connection to your MySQL database and resolve the "Connection refused" error.

The above is the detailed content of Why Am I Getting a 'Connection Refused' Error When Connecting to MySQL with PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn