Search

FAQ > PHP

Connecting to MySQL from your own scripts

How to connect to the MAMP PRO MySQL server from PHP scripts using the correct host, port, and credentials.

Connection Parameters

Parameter Value
Host localhost / 127.0.0.1 (depending on language and/or connection method used)
Port 8889
Username root
Password root
Socket /Applications/MAMP/tmp/mysql/mysql.sock

Examples

Use localhost as the host. PHP will automatically use the UNIX socket for local connections, which is faster than a TCP/IP connection.

<?php
  $db_host     = 'localhost';
  $db_user     = 'root';
  $db_password = 'root';
  $db_db       = 'mydatabase';

  $mysqli = @new mysqli(
    $db_host,
    $db_user,
    $db_password,
    $db_db
  );

  if ($mysqli->connect_error) {
    echo 'Errno: ' . $mysqli->connect_errno;
    echo '<br>';
    echo 'Error: ' . $mysqli->connect_error;
    exit();
  }

  echo 'Success: A proper connection to MySQL was made.';
  echo '<br>';
  echo 'Host information: ' . $mysqli->host_info;
  echo '<br>';
  echo 'Protocol version: ' . $mysqli->protocol_version;

  $mysqli->close();
?>
Connect via Network (TCP/IP)

Use 127.0.0.1 as the host and specify port 8889 explicitly. This method is required when the connection is made over the network or when a port must be provided.

<?php
  $db_host     = '127.0.0.1';
  $db_user     = 'root';
  $db_password = 'root';
  $db_db       = 'mydatabase';
  $db_port     = 8889;

  $mysqli = new mysqli(
    $db_host,
    $db_user,
    $db_password,
    $db_db,
    $db_port
  );

  if ($mysqli->connect_error) {
    echo 'Errno: ' . $mysqli->connect_errno;
    echo '<br>';
    echo 'Error: ' . $mysqli->connect_error;
    exit();
  }

  echo 'Success: A proper connection to MySQL was made.';
  echo '<br>';
  echo 'Host information: ' . $mysqli->host_info;
  echo '<br>';
  echo 'Protocol version: ' . $mysqli->protocol_version;

  $mysqli->close();
?>

Which method should I use? The UNIX socket connection (localhost) is faster and recommended when your script and the database server run on the same machine. Use the TCP/IP connection (127.0.0.1 with port 8889) when a port must be specified explicitly or the connection is made over a network.

Troubleshooting

Connection refused
Open MAMP PRO and verify that the MySQL server status is shown as active.

Access denied for user ‘root’
The username or password is incorrect. The default credentials are root / root.

Unknown database
The specified database does not exist. Create it first in phpMyAdmin, or directly in MAMP PRO by selecting your site and opening the Databases tab.

Can’t connect to MySQL server on ‘127.0.0.1:3306’
MAMP PRO does not necessarily use the default MySQL port 3306. To verify which port is configured, open MAMP PRO and go to Settings → Server → Ports. Use that port number in your script (e.g. $db_port = 8889).