Notes: Connect PHP5 to MySql in Mac OS X

I came across this error in my Apache error log file found in /var/log/apache2/error_log.

PHP Warning:  mysql_connect(): [2002] No such file or directory
(trying to connect via unix:///var/mysql/mysql.sock)

I figured out that this is due to PHP not being able to find the MySql socket to connect to the MySql database server. To be exact, PHP is looking for a file named mysql.sock.

I turned to look for mysql.sock in the MySql configuration file found in /usr/local/bin/mysql_config.

pkgincludedir='/usr/local/Cellar/mysql/5.6.13/include'
if [ -f "$basedir/include/mysql/mysql.h" ]; then
    pkgincludedir="$basedir/include/mysql"
elif [ -f "$basedir/include/mysql.h" ]; then
    pkgincludedir="$basedir/include"
fi

version='5.6.13'
socket='/tmp/mysql.sock'
ldflags=''

if [ 0 -eq 0 ]; then
    port=0
else
    port=3306
fi

# Create options

PHP was looking for the file /var/mysql/mysql.sock but the file exists in /tmp/mysql.sock.

So what I did was to simply create a symlink for the mysql.sock file in the /var/mysql/ folder.

$ sudo mkdir /var/mysql
$ ln -s /tmp/mysql.sock /var/mysql/mysql.sock

I could have modified the line in the mysql_config file to point to /var/mysql/mysql.sock but this is not good for other applications in Mac OS X that need the mysql.sock file in /tmp/mysql.sock.

Testing:

To test if indeed PHP can connect to MySql, I created a file named ~/Sites/test-php-mysql.php with the following contents.

<?php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'password';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error: Could not connect to MySql.');

    if ($conn) {
        echo 'Successfully connected to MySql.';
    }

    $dbname = 'mysql';
    mysql_select_db($dbname);
?>

Then I launched Safari and typed http://localhost/~darwin/test-php-mysql.php in the address bar. It showed that the connection was established.

Successfully connected to MySql.

It worked!