Warning: mysqli_connect(): (HY000/2002): No such file or directory

This one can be a pesky error to sort out, but no fear – we’ve got your back!

You’re probably here frustrated so lets get straight to the point. As you’ve probably already guessed, there’s a file or directory that cannot be found.

The full error possible looks something like this:

Warning: mysqli_connect(): (HY000/2002): No such file or directory in <directory path> on line <number> Failed to connect to MySQL: No such file or directory

For most causes though, this error is a little bit on the cryptic side. When I fixed most of these errors it’s not usually related to the file or directory explicitly, but the host. I’m sure you’ve already checked a million times that the file/directory does exist and pulled out much hair over it.

How To Fix

Check the host name! Whether you’re running XAMMP, AMPPS or using shared hosting, dedicated servers etc.

The simplest fix, although possibly not the most elegant is to change your connection references from ‘localhost‘ to ‘‘ – this will always work, no matter what your programing language or framework.

So in PHP your connection string would start:


The Elegant Route

Shouldn’t PHP know about localhost? Yes, but you need to configure in in your global settings to make it understand this. If you have shared hosting, this may have already been taken care for you. If you had a nice installer for your local web server of choice bundled with things like PHP then it might have sorted this for you. This may be why your scratching your head wondering why it isn’t working now.

There’s so many languages, frameworks, server software and setups that it’s impossible to cover the configuration of all in this article but if you’ve got any special requests, drop them in the comments below and we’ll see what we can do!


Just in case you haven’t done already, do actually check the file and directory exist. I know, I know, you’ve already done that but the article wouldn’t be completed without mentioning it! I’ve put it at the bottom so as not to distract from the likely fix to your problem above!

You may also like...

3 1 vote
Article Rating
Notify of
Inline Feedbacks
View all comments
2 years ago

I tried this, but now I get “Warning: mysqli_connect(): (HY000/2002): Connection refused in…”

Would love your thoughts, please comment.x