You may see:
• Connection refused
• Access denied for user
• Can’t connect to local MySQL server
• No such file or directory
These usually happen because:
❌ MySQL service is stopped
❌ Wrong socket path
❌ Incorrect credentials
❌ Wrong hostname
✅ Step 1: Check MySQL Service on macOS
For XAMPP:
- Open XAMPP Manager
- Start MySQL
For MAMP:
- Open MAMP
- Click Start Servers
For native MySQL:
Open terminal and run:
sudo mysql.server start
If MySQL is not running → PHP cannot connect.
✅ Step 2: Verify Database Credentials
Open your PHP file:
$host = "localhost";
$user = "root";
$password = "";
$database = "test_db";
✔ Database name correct
✔ Username correct
✔ Password correct
Check inside:
✅ Step 3: Fix Socket Error (Very Common on macOS)
Sometimes macOS uses a different MySQL socket path.
Try using:
$host = "127.0.0.1";
Instead of:
$host = "localhost";
💡 This solves connection refused issue in most cases.
✅ Step 4: Check MySQL Port
Default port:
👉 3306
In phpMyAdmin → Server Information → check port number.
If different, connect like:
$conn = mysqli_connect("127.0.0.1", "root", "", "test_db", 3307);
(Change port as needed)
✅ Step 5: Fix Access Denied Error
In phpMyAdmin:
✔ Go to User Accounts
✔ Edit privileges of root/user
✔ Allow all permissions
Save and retry.
🚀 Professional Error Handling Code
Always use this:
$conn = mysqli_connect($host, $user, $password, $database);
if (!$conn) {
die("MySQL Connection Failed: " . mysqli_connect_error());
}
This shows exact error reason.
📌 Common macOS Mistakes
❌ Forgetting to start MySQL server
❌ Using localhost instead of 127.0.0.1
❌ Wrong port number
❌ Permission issues
🎯 Final Words
On macOS, most PHP MySQL connection errors happen due to:
👉 MySQL not running
👉 Wrong host or socket
Once fixed properly, your PHP app will work smoothly.
If this helped you, share it with other Mac developers 😊