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

If you are trying to establish a connection handle by using PDO, you might have encountered this error: Warning: PDO::__construct() : 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!!




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.