Connect to MySQL from PHP
How to connect to the MAMP PRO MySQL server from PHP scripts using the correct host, port, and credentials.
| Parameter | Value |
|---|---|
| Host (socket) | localhost |
| Host (TCP/IP) | 127.0.0.1 |
| Port | 8889 |
| Username | root |
| Password | root (unless changed in MAMP PRO) |
| Socket | /Applications/MAMP/tmp/mysql/mysql.sock |
UNIX Socket (Recommended)
Section titled “UNIX Socket (Recommended)”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();?>TCP/IP
Section titled “TCP/IP”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();?>Troubleshooting
Section titled “Troubleshooting”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).