如何通过mysqli连接到不同的MySQL端口?

时间:2017-03-22 16:37:33

标签: php mysqli port

在PHP的mysqli doc中,它说

  

mysqli mysqli_connect([string $ host = ini_get(" mysqli.default_host")   [,string $ username = ini_get(" mysqli.default_user")[,string $ passwd   = ini_get(" mysqli.default_pw")[,string $ dbname ="" [,int $ port = ini_get(" mysqli.default_port")[,string $ socket =   ini_get(" mysqli.default_socket")]]]]]])

但是当我做的时候

$dblink = new \mysqli($c['host'], $c['user'], $c['pass'], $c['name'], $c['port']);

它连接到默认端口。 只有在我这样做之后

$dblink = new \mysqli($c['host'].":".$c['port'], $c['user'], $c['pass'], $c['name'], $c['port']);

是否连接到正确的端口。

3 个答案:

答案 0 :(得分:1)

The documentation of mysqli_connect() mentions:

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

This is the behaviour of the underlying libmysql library. It is also mentioned in the documentation of the deprecated mysql_connect() function where the solution is also provided:

Note:

Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost".

The behaviour is also specified in the documentation of PDO_MYSQL DSN but it is more obscure this time:

Note: Unix only:

When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

答案 1 :(得分:0)

连接到mysql后,您可以查看连接信息。

$dblink = new \mysqli($c['host'], $c['user'], $c['pass'], $c['name'], $c['port']); if ($dblink->connect_error) { die('Connect Error (' . $dblink->connect_errno . ') '. $dblink->connect_error); } echo $dblink->host_info;

答案 2 :(得分:0)

你是对的,不管别人怎么说。 根据我的测试,结果如下:

  1. 如果你将localhost留空,不管端口是什么,它都会连接到默认端口,不管最后一个参数是什么
  2. 如果你把字符串“localhost”作为本地主机,它仍然会连接到默认端口,不管最后一个参数是什么
  3. 仅当您将 localhost 设置为 127.0.0.1 或具有 MYSQL SERVER 的任何其他 IP 时,才会接受并使用最后一个参数。

所以,我的解决方案是如果用户选择一个空的本地主机,则强制本地主机为“127.0.0.1”,因此连接将被强制使用该端口。