mysqli使用localhost問題

<?php
$mysqli = new mysqli('localhost', 'root', '123456', 'mysql');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
};

echo 'ok';

  • 若是上面鏈接地址爲'localhost'就會報錯,以下:php

    Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /mnt/www/cglevi/publichtml/mysql.php on line 2 Connect Error (2002) No such file or directoryhtml

  • 將'localhost'修改成'127.0.0.1'以後連接正常mysql

  • 將代碼:sql

    $con = mysqli_connect("localhost","root","123456","mysql");安全

    修改成:app

    $con = mysqli_connect("127.0.0.1","root","123456","mysql");dom


查看了hosts沒有問題,以下:socket

127.0.0.1 localhost
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
/etc/hosts (END) 

查看mysql狀態,沒有問題,以下:性能

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.6.10, for Linux (x86_64) using  EditLine wrapper

Connection id:      860
Current database:   
Current user:       root@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.6.10 MySQL Community Server (GPL)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/lib/mysql/mysql.sock
Uptime:         13 hours 13 min 50 sec

Threads: 1  Questions: 11900  Slow queries: 0  Opens: 100  Flush tables: 1  Open tables: 80  Queries per second avg: 0.249
--------------

開始的回答有點不嚴謹,估計也沒有解決問題,修改了答案:ui

問題出現的緣由:

當主機填寫爲localhost時MySQL會採用 unix domain socket鏈接,當主機填寫爲127.0.0.1時MySQL會採用TCP/IP的方式鏈接。使用Unix socket的鏈接比TCP/IP的鏈接更加快速與安全。這是MySQL鏈接的特性,能夠參考官方文檔的說明4.2.2. Connecting to the MySQL Server

On Unix, MySQL programs treat the host name localhost specially, in a way that is 
likely different from what you expect compared to other network-based programs. 
For connections to localhost, MySQL programs attempt to connect to the local server 
by using a Unix socket file. This occurs even if a --port or -P option is given to 
specify a port number. To ensure that the client makes a TCP/IP connection to the 
local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP 
address or name of the local server. You can also specify the connection protocol 
explicitly, even for localhost, by using the --protocol=TCP option.

這個問題有如下幾種解決方法:

  1. 使用TCP/IP代替Unix socket。即在鏈接的時候將localhost換成127.0.0.1。
  2. 修改MySQL的配置文件my.cnf,指定mysql.socket的位置:

    /var/lib/mysql/mysql.sock (你的mysql.socket路徑)。

  3. 直接在php創建鏈接的時候指定my.socket的位置(官方文檔:mysqli_connect)。好比:

    $db = new MySQLi('localhost', 'root', 'root', 'my_db', '3306', '/var/run/mysqld/mysqld.sock')

其實答案寫的不是很嚴謹,不過既然被採納了,就多說一點。 一般意義上localhost127.0.0.1是等價的,只是mysql在處理這個名詞的問題上有一些不一樣,是根據不一樣的地址來採起的不一樣的通訊手段。

緣由呢,我猜大概是爲了本地應用能得到更好的性能。並且localhost這個地址在mysql中也不會作匹配。即user@'%'不能匹配到user@'localhost'

相關文章
相關標籤/搜索