在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']);
是否连接到正确的端口。
答案 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. IfPDO_MYSQL
is compiled againstlibmysqlclient
then the location of the socket file is atlibmysqlclient
's compiled in location. IfPDO_MYSQL
is compiled againstmysqlnd
a default socket can be set thru thepdo_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)
你是对的,不管别人怎么说。 根据我的测试,结果如下:
所以,我的解决方案是如果用户选择一个空的本地主机,则强制本地主机为“127.0.0.1”,因此连接将被强制使用该端口。