Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Using PHP with MySQL Connecting PHP to MySQL Getting Started with PDO

Database connect error using PDO

I am just trying the test product database and can't seem to connect using php. I can connect to the local database via terminal using root no problem.

database.php

<?php
$db = new PDO("mysql:host=localhost;dbname=shirts4mike,"root","PASSWORD");
var_dump($db);
?>

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory'

The fatal error seems to be looking for a file/dir just sure why. Thinking maybe it's not authorizing correctly - I have the correct credentials/port in database.php.

13 Answers

Well,

It does actually look like the issue in the terminal is that php cannot connect via socket so it seems like the issue corrected when I changed the host from "localhost" to "127.0.0.1" and made sure that I set the port in the PDO.

You could probably try to add the path to the socket in the my.cnf file (any one of them will do) and make sure your msyql.default_socket, mysqli.default_socket and pdo_mysql.default_socket match the "socket" value in my.cnf and see if that works for you.

Otherwise try

$db = new PDO("mysql:host=127.0.0.1;dbname=shirts4mike;port=3306", "root", "PASSWORD");

Just making sure to set the port to the port value that you need. Let me know if that works or if you're able to figure out a work around. Otherwise I'm not sure how to get the php to mysql connection working in the terminal.

This works for me

$db = new PDO("mysql:host=localhost;dbname=shirts4mike","root");
Scott Renshaw
Scott Renshaw
4,646 Points

Thank you, this worked for me.

Yes, this was the solution for me as well. In the installation video Randy mentioned that the default is no password, so there's no need to enter one here. Double-check the "users" tab in the PHPMyAdmin to see the users, passwords, and most importantly permissions. When I installed MySQL another way from another course (from MySQL website rather than with XAMPP) I noticed that the permissions were off for most users. I uninstalled everything (including the MySQL workbench), did a clean install of XAMPP only and everything is working beautifully with open permissions for all users (localhost, 127.0.0.1, etc.). Hope this helps someone! :-D

Jeremy thanks man! I can't believe it was just changing localhost to 127.0.0.1 sometimes it's the small things. It was throwing me for a loop because it worked using the cli and on the remote server. This totally worked locally (yay!) and I just left off the port as it's default.

$db = new PDO("mysql:host=127.0.0.1;dbname=shirts4mike","root","PASSWORD");

Awesome Tony!

Glad to hear it!

Can you copy and paste the full error? It might be a socket issue.

localhost/database.php error

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Users/tj/Dropbox/Development/php-pdo/database.php:2 Stack trace: #0 /Users/tj/Dropbox/Development/php-pdo/database.php(2): PDO->__construct('mysql:host=loca...', 'root', 'REMOVED.mys') #1 {main} thrown in /Users/tj/Dropbox/.../database.php on line 2

tried with non-root user

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Users/tj/Dropbox/Development/php-pdo/database.php:2 Stack trace: #0 /Users/tj/Dropbox/Development/php-pdo/database.php(2): PDO->__construct('mysql:host=loca...', 'tj@localhost', 'REMOVED') #1 {main} thrown in /Users/tj/Dropbox/.../database.php on line 2

even tried using php connect code from MySQL Workbench (warning not failure this time)

Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /Users/tj/Dropbox/.../database-workbench.php on line 9

Any input on these errors?

It's a local env issue as i pushed the same file and database up to the server and it worked fine...

Hey Tony,

Sorry to get back to you so late. Glad to see it's working on the live server.

For the localhost you might try adding the path to your mysld socket. I'm using MAMP so my path would look like this:

$db = new PDO("mysql:host=localhost;mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysqld.sock;dbname=shirts4mike;port=3306;","root","PASSWORD");

Just replace the path with your own path and see if that works.

Let me know!

Thanks for the try guys but unfortunately no dice. What I don't get is how it can work when I login via command line using the same root user and pass but not via php. Any other ideas?

$db = new PDO("mysql:host=localhost;mysql:unix_socket=/tmp/mysql.sock;dbname=shirts4mike;","root","PASSWORD");

This is the error I get loading http://localhost/php-pdo/database-test.php

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Library/WebServer/Documents/php-pdo/database-test.php:2 Stack trace: #0 /Library/WebServer/Documents/php-pdo/database-test.php(2): PDO->__construct('mysql:host=loca...', 'root', 'PASSWORD') #1 {main} thrown in /Library/WebServer/Documents/php-pdo/database-test.php on line 2

I can login to the database just find

mysql> status
--------------
mysql  Ver 14.14 Distrib 5.6.19, for osx10.9 (x86_64) using  EditLine wrapper

Connection id:    15
Current database: 
Current user:   root@localhost
SSL:      Not in use
Current pager:    stdout
Using outfile:    ''
Using delimiter:  ;
Server version:   5.6.19 Homebrew
Protocol version: 10
Connection:   Localhost via UNIX socket
Server characterset:  utf8
Db     characterset:  utf8
Client characterset:  utf8
Conn.  characterset:  utf8
UNIX socket:    /tmp/mysql.sock
Uptime:     1 hour 44 min 5 sec

Threads: 3  Questions: 195  Slow queries: 0  Opens: 93  Flush tables: 1  Open tables: 86  Queries per second avg: 0.031
--------------

mysql> USE shirts4mike;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> status
--------------
mysql  Ver 14.14 Distrib 5.6.19, for osx10.9 (x86_64) using  EditLine wrapper

Connection id:    15
Current database: shirts4mike
Current user:   root@localhost
SSL:      Not in use
Current pager:    stdout
Using outfile:    ''
Using delimiter:  ;
Server version:   5.6.19 Homebrew
Protocol version: 10
Connection:   Localhost via UNIX socket
Server characterset:  utf8
Db     characterset:  utf8
Client characterset:  utf8
Conn.  characterset:  utf8
UNIX socket:    /tmp/mysql.sock
Uptime:     1 hour 44 min 16 sec

Threads: 3  Questions: 203  Slow queries: 0  Opens: 93  Flush tables: 1  Open tables: 86  Queries per second avg: 0.032
--------------

mysql> SHOW TABLES;
+-----------------------+
| Tables_in_shirts4mike |
+-----------------------+
| products              |
+-----------------------+
1 row in set (0.00 sec)

mysql>

Hmmm...

The next thing I could think of would be to either try using 127.0.0.1 instead of "localhost" if you haven't already. Or check your php.ini file to make sure the mysql.default_socket setting is the same as "/tmp/mysql.sock".

That definitely seems like a socket issue to me, or otherwise a php settings issue. Would you be willing to post your php.ini file here?

Sure here is what I found and saved the php.ini file

$ tj$ mdfind -name php.ini
/private/etc/php.ini.default-5.2-previous
/private/etc/php.ini.default
$ tj$ cat /private/etc/php.ini.default

I also just checked what php user is being used at localhost/php-pdo/user.php

<?php echo exec('whoami'); ?> 

and it displayed _www which is just the default apache user

Ok,

in your php.ini file you have several sockets listed. Since there is a pdo_mysql.default_socket, that's probably your main concern but you could set the rest just to be safe.

mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock
pdo_mysql.default_socket = /tmp/mysql.sock

If that doesn't work, we can check out

<?php phpinfo(); ?>

And see if there's some useful information there.

I updated the php.ini with sockets

-r--r--r--   1 root  wheel    65K Jul 15 19:21 php.ini.default

; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
mysql.default_socket= /tmp/mysql.sock
mysqli.default_socket= /tmp/mysql.sock
pdo_mysql.default_socket= /tmp/mysql.sock

$sudo apachectl restart

Unfortunately, still getting error on localhost/php-pdo/database.php

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in ..."

Here ia some of the output from phpinfo.php let me know if you want any specific data. It doesn't paste well into text.

PHP Version 5.4.24

System  
Darwin <user>.local 13.2.0 Darwin Kernel Version 13.2.0: Thu Apr 17 23:03:13 PDT 2014; root:xnu-2422.100.13~1/RELEASE_X86_64 x86_64

Virtual Directory Support 
disabled

Configuration File (php.ini) Path 
/etc

Scan this dir for additional .ini files
/Library/Server/Web/Config/php

Additional .ini files parsed
(none)
...

Registered PHP Streams  
https, ftps, compress.zlib, compress.bzip2, php, file, glob, data, http, ftp, phar, zip

...

CONFIGURATION
apache2handler

Apache Version  
Apache/2.2.26 (Unix) DAV/2 PHP/5.4.24 mod_ssl/2.2.26 OpenSSL/0.9.8y

Apache Version  
Apache/2.2.26 (Unix) DAV/2 PHP/5.4.24 mod_ssl/2.2.26 OpenSSL/0.9.8y

Apache API Version  
20051115

Server Administrator  
you@example.com

Hostname:Port 
<username>.local:0

User/Group  
_www(70)/70

Max Requests  
Per Child: 0 - Keep Alive: on - Max Per Connection: 100

Timeouts  
Connection: 300 - Keep-Alive: 5

Virtual Server  
No

Server Root 
/usr

Loaded Modules  
core prefork http_core mod_so mod_authn_file mod_authn_dbm mod_authn_anon mod_authn_dbd mod_authn_default mod_authz_host mod_authz_groupfile mod_authz_user mod_authz_dbm mod_authz_owner mod_authz_default mod_auth_basic mod_auth_digest mod_cache mod_disk_cache mod_mem_cache mod_dbd mod_dumpio mod_reqtimeout mod_ext_filter mod_include mod_filter mod_substitute mod_deflate mod_log_config mod_log_forensic mod_logio mod_env mod_mime_magic mod_cern_meta mod_expires mod_headers mod_ident mod_usertrack mod_setenvif mod_version mod_proxy mod_proxy_connect mod_proxy_ftp mod_proxy_http mod_proxy_scgi mod_proxy_ajp mod_proxy_balancer mod_ssl mod_mime mod_dav mod_status mod_autoindex mod_asis mod_info mod_cgi mod_dav_fs mod_vhost_alias mod_negotiation mod_dir mod_imagemap mod_actions mod_speling mod_userdir mod_alias mod_rewrite mod_php5 mod_hfs_apple2

...

Apache Environment
Variable | Value

HTTP_HOST | localhost
HTTP_CONNECTION | keep-alive
HTTP_ACCEPT | text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
...
SERVER_NAME | localhost
DOCUMENT_ROOT | /Library/WebServer/Documents
SCRIPT_FILENAME | /Library/WebServer/Documents/php-pdo/phpinfo.php
REMOTE_PORT | 53338
...

tons more stuff...