【问题标题】:Able to connect to mysql via sequelpro but not via PHP wordpress code?能够通过 sequelpro 但不能通过 PHP wordpress 代码连接到 mysql?
【发布时间】:2020-11-30 22:58:19
【问题描述】:

很奇怪的问题。

在我的 Mac 上,我设置了 apache、mysql 等来在本地进行一些 wordpress / PHP 开发。

mysql安装正常,这是下面的版本

mysql  Ver 8.0.22 for osx10.16 on x86_64 (Homebrew)

我可以通过 app sequel pro 连接到它,创建/管理数据库。

但是,当我设置一个 wordpress 网站或通过 PHP 测试连接时。我终生无法连接到它。

这是我的 wordpress config.php 文件的 db 部分:

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'root' );

/** MySQL database password */
define( 'DB_PASSWORD', 'password' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

这是我尝试继续安装 wordpress 时得到的页面:

我还尝试了一个简单的 PHP 脚本,如下所示:

<?php

$c = new mysqli("localhost", "root", "password", "wordpress") or die('Could not connect the database : Username or password incorrect');
echo 'Database Connected successfully';

?>

我得到这个错误:

Warning: mysqli::__construct(): (HY000/2002): No such file or directory

如果我将 localhost 更改为 127.0.0.1 我会收到此错误:

Warning: Packets out of order. Expected 0 received 1. Packet size=68 in /users/asdasda/test.php on line 3
Warning: mysqli::__construct(): MySQL server has gone away in /users/asdasda/test.php on line 3
Warning: mysqli::__construct(): Error while reading greeting packet. PID=36547 in /users/asdasda/test.php on line 3

【问题讨论】:

  • 你是如何安装 apache/php 的?
  • @mikeroq 使用 brew

标签: php mysql mysqli mariadb


【解决方案1】:

好的,我想通了。

我必须在/etc/ 中创建一个php.ini 文件,其中包含以下几行:

mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock
pdo_mysql.default_socket=/tmp/mysql.sock

【讨论】:

    【解决方案2】:

    根据this answer here

    您应该避免使用 localhost 而是使用 IP。 localhost 使用 IP 地址 127.0.0.1

    【讨论】:

    • 这是一个非常糟糕的方法,因为它强制数据库通信使用 TCP/IP 而不是本地套接字(这会更有效)。正确的做法是配置PHP指向正确的socket文件。
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2019-03-06
    • 2017-05-21
    • 2012-02-03
    • 1970-01-01
    • 2020-12-25
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多