Connecting to MYSQLi through Terminal in Mac OS using MAMP

macos, mamp, mysql, mysqli, php

Solution

Had the same issue. Here's what I did.

Open Terminal (/Applications/Utilities/terminal.app)

Use your favorite text editor to create/edit `~/.bash_profile`. For instance, if you're using vim, type `vim ~/.bash_profile`. I use TextMate, so I typed `mate ~/.bash_profile`.

Add these lines:

export MAMP_SQL=/Applications/MAMP/Library/bin 
export MAMP_PHP=/Applications/MAMP/bin/php/php5.5.10/bin
export PATH="$MAMP_SQL:$MAMP_PHP:$PATH"

These lines ensure that the first versions of MySQL and PHP that are found (and therefore used) are the versions used by MAMP. NB: Make sure that php5.5.10 matches the version MAMP is using. You can check this against `http://localhost:8888/MAMP/index.php?page=phpinfo&language=English` by default. SAVE THE FILE (I shouldn't have to save this, but invariably someone complains that it doesn't work).

Close your terminal window and reopen. This restarts the shell, which will load your `.bash_profile` script.

Type `which php`. You should get something akin to `/Applications/MAMP/bin/php/php5.5.10/bin/php`

Type `which mysql`. You should get something akin to `/Applications/MAMP/Library/bin/mysql`

If for any reason you get something different than the responses from 5 and 6, go back and check your .bash_profile; chances are you just neglected to save it properly.

Problem

I am trying to run my PHP script via Terminal in Mac. When I try to run the script, I am getting this error: Warning: mysqli_connect(): (HY000/2002): No such file or directory This is how I am trying to connect: mysqli_connect('localhost','root','root','my_db'); I also tried to connect using the host: 127.0.0.1 instead of localhost and I then got this error: Warning: mysqli_connect(): (HY000/2002): Connection refused From what I've read online it might have something to do with mysql socket, but whatever I try to do to get this to work doesn't help. I even tried to connect using the following as my host: :/Applications/MAMP/tmp/mysql/mysql.sock :/var/mysql/mysql.sock Any idea what can be the problem/solution?

Original source