2

I'm setting up a PDO connection in a test script:

use app\SomeDAO;

class SomeTest extends \PHPUnit_Framework_TestCase
{
    protected $db;

    public function setUp()
    {
        $dsn = "mysql:host=localhost;dbname=baseball;user=root;password=root";
        $this->db = new PDO($dsn);
    }

I'm getting an error:

PDOException: SQLSTATE[HY000] [2002] No such file or directory.

How can I use PDO here?

scrowler
  • 24,273
  • 9
  • 60
  • 92
krisacorn
  • 831
  • 2
  • 13
  • 23

2 Answers2

6

In Unix based (like linux, bsd, or OS X) systems, with MySQL localhost is secret code for try-to-use-a-socket, unless a you force it via a protocol flag to not do this (and no one ever does this). Just remember localhost usually equals socket file.

If Mysql in your MAMP is running in non-socket mode, you can try replacing the host value with 127.0.0.1 which connects via TCP on via port to the local machine--you'll need to figure out which port it's running on if it's not the default port.

If you look at the MAMP start script

  less /Applications/MAMP/bin/startMysql.sh

You can see if it's starting in socket mode, and what file it's using if it has a config param like:

  --socket=/Applications/MAMP/tmp/mysql/mysql.sock 

You can also investigate what open socket mysql might be using by following the answer in this question: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'

If you're running in socket mode, you need to make sure PDO knows the path to the socket file. One way to do this is specify the unix_socket instead of host in the dsn:

  $dsn =  "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=baseball;user=root;password=root";
Community
  • 1
  • 1
Ray
  • 40,256
  • 21
  • 101
  • 138
  • I'm believe I am running in socket mode because I can access pdo everywhere else with localhost. I tried the 127.0.0.1, but the connection was refused. – krisacorn Aug 05 '14 at 20:57
0

I had problem like that at MAMP. My decided it, when I connected with PDO I used next line code:

$this->pdo = new \PDO("mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;port=8889;dbname=mydatabase;charset=utf8", 'root', 'root');
Rashid
  • 1