Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to different machine, 'Can't connect through socket' Error

Tags:

php

mysql

pdo

I'm trying to connect to a different machine:

$this->_connection = new PDO("mysql: host=MYSQL_SERVER; dbname=MYSQL_DATABASE",MYSQL_USER, MYSQL_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

But PDO barfs:

SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Infuriatingly, this worked fine with localhost on my dev server - our production setup is an LVS with a separate DB server though, and I can't seem to get PDO to connect to it!

Where, oh where have I bungled what here?

Edit:

This works:

mysql_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD) or die(mysql_error());
mysql_select_db(MYSQL_DATABASE) or die(mysql_error());;
echo 'Connected to database <br/>';

Note: MYSQL_SERVER is not localhost, it is the IP of our database master server. On our dev server, which hosts the dev database, PDO works flawlessly.

like image 718
Michael Robinson Avatar asked May 28 '26 15:05

Michael Robinson


1 Answers

It's very simple. Your DSN is flawed.

Use this:

$this->_connection = new PDO("mysql:host=EXTERNAL_IP;dbname=DB", USERNAME, PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

Try it and report back.

like image 143
Theodore R. Smith Avatar answered May 31 '26 06:05

Theodore R. Smith