How to connect to MySQL in PHP on Mac OS X

Enabling PHP on Mac OS X is pretty straightforward (it’s preinstalled from OS X 10.5 onwards):

  1. Uncomment LoadModule php5_module in /etc/apache2/httpd.conf
  2. Start up Web Sharing in System Preferences

However, even after doing that, my PHP-based website still couldn’t connect to it’s MySQL database. It just showed this error when I tried to load the site:

Database Error: Unable to connect to the Database: Could not connect to MySQL.

All of the database settings in my app (a Joomla website) were correct, but still I couldn’t get it to work.

It turns out that the problem is due to conflicting socket locations between OS X and other types of UNIX. In my case PHP was configured to access MySQL (locally) at /var/mysql/mysql.sock whereas the socket was really at /tmp/mysql.sock. Changing this in the PHP config fixed the problem

Solution

Create a custom PHP settings file:

sudo cp /etc/php.ini.default /etc/php.ini

then edit the default_socket definition for your database driver to point to the correct socket.In my case the driver is the default MySQL driver and the correct socket is /tmp/mysql.sock, so it changed from this:

; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
mysql.default_socket = /var/mysql/mysql.sock

to this:

; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
mysql.default_socket = /tmp/mysql.sock

It’s important to note that there will be several definitions of default_socket for different drivers (each of which has a different prefix for it’s settings) so it’s important that you change the correct one, based on what your app is using.

After doing this restart Web Sharing (in System Preferences) and everything should work

Advertisements

About this entry