On an Apache server, MySQL can’t connect when you use localhost, but it work when you chane to IP address 127.0.0.1
When you use “localhost”, it use socket for connecting to MySQL server, this is faster than using TCP/IP connection, that is used when you use IP address to connect to MySQL server.
First find out socket path. To do this login to MySQL server, run
show variables like "socket";
See if you can connect using this socket with command
mysql -S /var/lib/mysql/mysql.sock -u root -p
In this cause, login to MySQL using socket worked.
I created a simple test PHP script to verify MySQL connection, it was able to connect to MySQL server using “localhost”.
Same script did not work when i try access it using web server. So the problem is web server user not able to connect to MySQL socket. You need to check permission for socket and parrent folders. In this case problem is fixed by running
chmod 755 /var/lib/mysql/You can verify enabling SSH access for web server user, then connect to MySQL using command line or try access socket file as apache user.
MySQL Socket Path in php.ini
When a PHP application use localhost to connect, PHP find location of socket from php.ini, you need to verify this path set in php.ini is same as the socket path used by MySQL server.
# cat /etc/php.ini | grep socket ; Default timeout for socket based streams (seconds) ; http://php.net/default-socket-timeout default_socket_timeout = 60 ;extension=php_sockets.dll ; Default socket name for local MySQL connects. If empty, uses the built-in ; http://php.net/pdo_mysql.default-socket pdo_mysql.default_socket= /var/lib/mysql/mysql.sock ; Default socket name for local MySQL connects. If empty, uses the built-in ; http://php.net/mysql.default-socket mysql.default_socket = /var/lib/mysql/mysql.sock ; Default socket name for local MySQL connects. If empty, uses the built-in ; http://php.net/mysqli.default-socket mysqli.default_socket = /var/lib/mysql/mysql.sock #If path is differnt, you need to make it same. You can either modify php.ini or MySQL server config file.