본문 바로가기

FALL in/G.MA's 개발일지

php, mysql 연결 실패 문제

<?php

if(!$conn = mysqli_connect('localhost', '사용자계정', '패스워드')) echo "mysql 연결실패<br/>";

else echo "mysql 연결성공<br/>";

?>


위와 같은 간단한 php를 만들어 php와 mysql 연결을 테스트해봤을때 계속 mysql연결실패가 나왔었다. 

오류는  No such file or directory  이다.

구글에 검색해보고 많은 시도를 해본결과 

php의 mysql 소켓과 mysql의 mysql 소켓이 서로 다른곳에 있다는 문제였다.

php info를 실행해보면

mysql.default_socket/var/mysql/mysql.sock

mysql소켓이 위의 위치에 있는걸 알수있는데


mysql에서 status; 를 입력하면

UNIX socket: /tmp/mysql.sock

소켓이 위의 위치에 있다는걸 알수있다.




해결은 https://stackoverflow.com/questions/4219970/warning-mysql-connect-2002-no-such-file-or-directory-trying-to-connect-vi

For some reason mysql on OS X gets the locations of the required socket file a bit wrong, but thankfully the solution is as simple as setting up a symbolic link.

You may have a socket (appearing as a zero length file) as /tmp/mysql.sock or /var/mysql/mysql.sock but 1 or more apps is looking in the other location for it.

Rather than move the socket and have to edit config files and remember to keep edited files local and away from servers where the paths are correct, simply create a symbolic link so your mac finds the required socket, even when it's looking in the wrong place!

If you have /tmp/mysql.sock but no /var/mysql/mysql.sock then...

cd /var 
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /tmp/mysql.sock mysql.sock

If you have /var/mysql/mysql.sock but no /tmp/mysql.sock then

cd /tmp
ln -s /var/mysql/mysql.sock mysql.sock

You will need permissions to create the directory and link, so just prefix the commands above with sudo if necessary.

Hope this helps. It has sorted this exact issue for me on 3 macs so far.