When troubleshooting PHP database connection issues, the first place to check is always the MySQL error log. On macOS, MySQL doesn't follow the traditional Linux path convention. Here are the most common locations:
/usr/local/mysql/data/*.err
/Library/MySQL/Logs/mysql_error.log
~/Library/Logs/MySQL/mysql.log
The definitive way to find your MySQL log location is to check the configuration:
# Connect to MySQL server
mysql -u root -p
# Run this SQL query
SHOW VARIABLES LIKE 'log_error';
If no error log is configured, add these lines to your my.cnf (usually located at /etc/my.cnf or /usr/local/etc/my.cnf):
[mysqld]
log-error=/usr/local/mysql/logs/mysql_error.log
general_log=1
general_log_file=/usr/local/mysql/logs/mysql_query.log
When dealing with connection failures, add error handling to your PHP code:
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
error_log("Connection failed: " . $e->getMessage());
echo "Check MySQL error log at: /usr/local/mysql/data/mysqld.local.err";
}
?>
For complex issues, enable slow query logging and examine performance:
# In MySQL configuration
slow_query_log = 1
slow_query_log_file = /usr/local/mysql/logs/mysql-slow.log
long_query_time = 2
log_queries_not_using_indexes = 1
Set up a simple shell script to watch for new errors:
#!/bin/bash
tail -f /usr/local/mysql/data/mysqld.local.err | grep --color -i -e "error" -e "warning"
When troubleshooting PHP database connection errors, MySQL logs are your first stop for diagnostics. On macOS, common locations include:
/usr/local/mysql/data/
/usr/local/var/mysql/
~/Library/Logs/MySQL/
Check your active log file location by connecting to MySQL and running:
SHOW VARIABLES LIKE 'log_error';
For a complete configuration check:
SHOW VARIABLES LIKE '%log%';
Add these lines to your my.cnf (typically at /etc/my.cnf or /usr/local/etc/my.cnf):
[mysqld]
log-error=/usr/local/var/mysql/mysql_error.log
general_log=1
general_log_file=/usr/local/var/mysql/mysql_query.log
Typical errors you might find in logs when PHP fails to connect:
ERROR 1045 (28000): Access denied for user
ERROR 2002 (HY000): Can't connect to local MySQL server
Use this PHP snippet to test connections with detailed error reporting:
<?php
$link = mysqli_connect("localhost", "user", "password", "db");
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($link);
?>
For PDO connections:
try {
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
Ensure the MySQL user has proper permissions:
GRANT ALL PRIVILEGES ON database.* TO 'username'@'localhost' IDENTIFIED BY 'password';