在Mac OS上使用MAMP通过终端连接MYSQLi

3
我正在尝试在Mac终端上运行PHP脚本。当我尝试运行脚本时,出现以下错误:
警告:mysqli_connect():(HY000/2002):没有这样的文件或目录
连接方式如下:
mysqli_connect('localhost','root','root','my_db');
我还尝试使用主机127.0.0.1进行连接,但是我得到了以下错误:
警告:mysqli_connect():(HY000/2002):拒绝连接
根据我在网上阅读的内容,这可能与mysql套接字有关,但是无论我尝试什么都不能解决问题。
我甚至尝试使用以下内容作为我的主机:
:/Applications/MAMP/tmp/mysql/mysql.sock
:/var/mysql/mysql.sock
有任何想法可以解决这个问题吗?

MySQL 是否真的在你的电脑上运行? - user1864610
是的,在我的浏览器上运行良好,没有错误... - Daniel
2个回答

3

我遇到了相同的问题。这是我的解决方法。

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

  2. 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.

  3. 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).

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

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

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

如果您从5和6的响应中收到与预期不同的结果,那么请返回并检查您的.bash_profile文件;很可能是您没有正确保存它。

谢谢,这个对我很有帮助,非常感激你给出了这个问题的最佳唯一答案! - Daniel

0
如果您在计算机上安装了MySQL,您可以执行以下命令:
mysql -u "username"

将“username”替换为您计算机的用户名

注意:通常情况下,root不起作用,请尝试使用您计算机的用户名


是的,这个确实可以工作,但这不是我遇到的问题。我正在尝试通过 PHP 脚本本身建立连接。我基本上想通过终端运行我的脚本。 - Daniel
也许尝试运行sudo php yourfile.php。 - elliotanderson
这不应该是一个权限错误,因为它实际上尝试运行脚本,唯一遇到的错误是连接到mysql。无论如何,我已经尝试使用sudo,但迄今为止仍然出现相同的错误... - Daniel
也许这只是一个简单的错误?进入phpmyadmin并确保您输入的用户名和密码是正确的。 - elliotanderson
我确信我的用户名、密码或数据库信息没有任何问题。如果我通过浏览器运行脚本,我可以正常运行,没有连接错误。但是当我使用终端时,问题才会出现。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接