mysql_connect() Difference between localhost and 127.0.0.1

匿名 (未验证) 提交于 2019-12-03 01:01:02

问题:

Now I have a config file as follows:

<?php return array(     'server'=>'localhost',     'username'=>'root',     'password'=>'123456',     'dbname'=>'duxiu',     'charset'=>'utf8' ); 

I'm cunfused about the time it spends when I using tow methods to connect mysql follows:

1.

<?php class Mysql{     private $conn;      public function __construct($c){         $this->conn=mysql_connect($c['server'],$c['username'],$c['password'],true) or die("连接出错");            mysql_select_db($c['dbname'],$this->conn);         if(isset($c['charset'])){             mysql_query("set names ".$c['charset'],$this->conn);         }     } } $c=require('config.php'); var_dump($c); $db=new Mysql($c); 

It spends 1.012 second.

2.when I using as following:

<?php class Mysql{     private $conn;      public function __construct($c){         $this->conn=mysql_connect($c['server'],$c['username'],$c['password'],true) or die("connect error");            mysql_select_db($c['dbname'],$this->conn);         if(isset($c['charset'])){             mysql_query("set names ".$c['charset'],$this->conn);         }     } } $c=array('server'=>'127.0.0.1','username'=>'root','password'=>'123456','dbname'=>'duxiu','charset'=>'utf8'); var_dump($c); $db=new Mysql($c); 

Now it spends 0.012 second .

Why?

回答1:

Difference: When you are using 127.0.0.1 instead of localhost, PHP will try to establish a TCP connection to mysql rather than using a UNIX domain socket.

Regulary it should be faster to use UNIX domain sockets but it seems in your application this is not the case as it takes very long to connect using the UNIX domain socket. Have you modified the php.ini value mysql.default_socket or pdo_mysql.default_socket? It should be empty by default. If not can you post that value?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!