问题
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?
回答1:
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, typevim ~/.bash_profile
. I use TextMate, so I typedmate ~/.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.
回答2:
If you have MySQL installed on your computer, you can do the following command:
mysql -u "username"
replacing "username" with the username of your computer
NOTE: often times root does not work, try the username of your computer
来源:https://stackoverflow.com/questions/20458864/connecting-to-mysqli-through-terminal-in-mac-os-using-mamp