0

Hello I am trying to connect to mysql server from php using PDO.

But I get this error :

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

Note that this is not a database I host. I was simply given the username and password to construct the database, create the users etc.

function ConnectToDb()
{
    try{
        $dns = 'mysql:host=1.1.1.1;dbname=dummyDbName';
        $username = 'dummyUser';
        $password = 'dummyPassword';
        $LINK = new PDO($dns, $username, $password);
        $LINK->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        if (!$LINK){
            die('Could not connect : ' .mysql_error());
        }
        else{
            return $LINK;
        }
    } catch (PDOException $ex){
        echo "An error occured : " .$ex->getMessage();
    }
}

I know that this works on localhost. I'm using it no problem, but as soon as I try to connect to the production database it fails. Anyone has an hint?

  • Is the production database on an ip or are you using localhost? Are you sure you have deployed the code- it is trying to connect to localhost, not an ip. – jynus Dec 30 '14 at 11:49
  • you may need to include --host parametre and giving either hostname or ip afterwards – Nawaz Sohail Jan 1 '15 at 7:42
  • @jynus Sorry for the late reply. The database is on an ip. I did deploy the code with the code to try to connect to that IP – Ben Lefebvre Jan 9 '15 at 3:10
  • @NawazSohail how do I know which parameter I need to include? Sorry if this is a newbie question, but hey it's my first time trying to connect to database which isn't localhost :P – Ben Lefebvre Jan 9 '15 at 3:13
  • You do not need to include host and port if you are using defaults..localhost and 3306 are the defaults one..if you are connecting to host and port other than default you need to mention in your mysql connect statement or you can also use environment variables as well..hope it helps – Nawaz Sohail Jan 9 '15 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.