Skip to content
MAMP PRO Documentation

Connect to MySQL from PHP

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

ParameterValue
Host (socket)localhost
Host (TCP/IP)127.0.0.1
Port8889
Usernameroot
Passwordroot (unless changed in MAMP PRO)
Socket/Applications/MAMP/tmp/mysql/mysql.sock

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

<?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 . '<br>';
echo 'Error: ' . $mysqli->connect_error;
exit();
}
echo 'Success: A proper connection to MySQL was made.<br>';
echo 'Host information: ' . $mysqli->host_info . '<br>';
echo 'Protocol version: ' . $mysqli->protocol_version;
$mysqli->close();
?>

Use 127.0.0.1 as the host and specify port 8889 explicitly. Required when the connection is made over a 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 . '<br>';
echo 'Error: ' . $mysqli->connect_error;
exit();
}
echo 'Success: A proper connection to MySQL was made.<br>';
echo 'Host information: ' . $mysqli->host_info . '<br>';
echo 'Protocol version: ' . $mysqli->protocol_version;
$mysqli->close();
?>

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

Access denied for user ‘root’
The username or password is incorrect. The default password is root, but if you changed it in MAMP PRO, use that password instead. See How to change the MySQL password.

Unknown database
The specified database does not exist. Create it first in phpMyAdmin or in MAMP PRO via the Databases tab.

Can’t connect to MySQL server on ‘127.0.0.1:3306’
MAMP PRO may not use port 3306. Check the configured port under Settings › Server › Ports and update your script accordingly (e.g. $db_port = 8889).


PHP how-to guides