PHP PDO + Warning: PDO::__construct() [pdo.–construct]: [2002] Invalid argument (trying to connect via unix://)

Assumptions:

  • You are using a linux distro
  • You are using XAMPP

PDO Constructor Error

If you are trying to establish a connection handle by using PDO, you might have encountered this error: “Warning: PDO::__construct() [pdo.–construct]: [2002] Invalid argument (trying to connect via unix://)

Solutions:

SOLN 1: for your host name, specify 127.0.0.1 instead of locahost

SOLN 2: Open your php.ini and set the following: pdo_mysql.default_socket=”/opt/lampp/var/mysql/mysql.sock”

SOLN 3: By specifying the PORT along with localhost, example:

$dbh = new PDO(“mysql:host=$hostname:3306;dbname=$dbname”, $username, $password);

How To Know Which Port Is Being Used For Your MySql?

1) Have a look at the entry in /etc/services

Open your Bash Terminal and execute the statement: sudo gedit /etc/services

And this will open up ‘services’ in the Text files ‘gedit’. Now do a search for ‘mysql’; you should find an entry similar to: “mysql 3306/tcp”. So 3306 is the port

2) Specify the port in your php.ini for mysql.default_port

NOTE:

=> If you are modifying your php.ini, do NOT forget to restart your xampp!!

If You Appreciate What I Do Here On Seven PHP :: 7PHP, You Could Consider:

  1. Following me on Twitter | @7php
  2. LIKE-ing my FaceBook page
  3. Subscribe to my Email List - see top-right subscription box
  4. Help diffuse this interview to the PHP ecosystem - Share & Spread the word as far as you can ==> That would be a FREE way to thank me
  5. Use my DigitalOcean referral link if you plan to use it as your VPS (it starts at only $5/month btw) or if you can refer it to your friends, highly appreciated.
  6. Support via Paypal donate - my Paypal ID is w@7php.com

{I'm thankful to your response(s)!}

Speak Your Mind

*